How do you observe the width of an element in polymer?

北慕城南 提交于 2019-12-13 04:48:46

问题


I was wondering how it is possible to observe changes to an element's css property such as the width.

I tried doing this but it didn't work. Where did I go wrong? Is it possible?

<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>

In this example, I'm trying to observe the clientWidth property which you can normally access from outside.


回答1:


There is a certain technique abusing CSS transitions and listening for the transitionend event. There are only a very few cases where it's really required (like if you want to adjust the resolution of a webgl context after the canvas dimensions changed in any way)

Add a transition in css to make the transition event fire when width/height change.

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

Listen for the event and handle whatever you want to happen

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

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



来源:https://stackoverflow.com/questions/26692678/how-do-you-observe-the-width-of-an-element-in-polymer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!