你如何观察聚合物中元素的宽度?

时间:2014-11-01 20:04:29

标签: javascript css dom polymer

我想知道如何观察元素的css属性(如宽度)的变化。

我试过这样做,但它没有用。我哪里做错了?有可能吗?

<polymer-element name="test-resize" attributes="elementWidth">
  <template>
    <p>elementWidth : {{elementWidth}}</p>
  </template>
  <script>
    Polymer({
      elementWidth: 100,
      observe: {
        "clientWidth" : "updateWidth",
      },
      updateWidth: function(oldValue, newValue){
        this.elementWidth = newValue;
      }
    });
  </script>
</polymer-element>

在此示例中,我尝试观察您通常可以从外部访问的clientWidth属性。

1 个答案:

答案 0 :(得分:4)

有一种技术滥用CSS转换并监听transitionend事件。实际需要的情况很少(例如,如果你想在画布尺寸以任何方式改变之后调整webgl上下文的分辨率)

在css中添加转换,以便在宽度/高度更改时触发转换事件。

:host {
  transition:width 0.01s, height 0.01s;
}

倾听事件并处理您想要发生的任何事情

this.addEventListener("transitionend",function(e){
  this.elementWidth = this.clientWidth;
}) 

more info about implementing the technique, like polyfills you'll probably need

相关问题