简体   繁体   English

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

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

I was wondering how it is possible to observe changes to an element's css property such as the width. 我想知道如何观察元素的CSS属性(例如宽度)的变化。

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. 在此示例中,我尝试观察通常可以从外部访问的clientWidth属性。

There is a certain technique abusing CSS transitions and listening for the transitionend event. 有某种技巧会滥用CSS过渡并监听transitionend事件。 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) 仅在极少数情况下确实需要它(例如,如果您想以任何方式更改画布尺寸后调整webgl上下文的分辨率)

Add a transition in css to make the transition event fire when width/height change. 在CSS中添加转场,以使转场事件在宽度/高度更改时触发。

: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 有关实施该技术的更多信息,例如您可能需要的polyfills

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM