观察元素样式更改(高度)

时间:2016-01-14 19:09:12

标签: polymer

我想通知元素样式更改的任何更改(在我的情况下:对元素高度的任何更改)。

我试图手动注册一个观察者:

  observers: [
    'heightUpdated(style.height)',
  ],

这似乎不适用(对于任何样式属性)。

我还尝试了另一位观察员:

  observers: [
    'heightUpdated(clientHeight)',
  ],

这名观察者永远不会被召唤。

1 个答案:

答案 0 :(得分:2)

我发现观察者更改Polymer元素的样式属性的唯一方法是使用MutationObserver

可以轻松设置以监听任何.style的任何更改。属性如.style.height,但它有很多限制。

Here是我之前设置的

Polymer({
  is: "my-element",
  properties: {

    // Saved to the element, so you can inspect it if you want
    mutationObserver: {
      value: function() {

        // uses the function "mutated" defined later"
        var observer = new MutationObserver(this.mutated.bind(this));
        observer.observe(this, { 

          // Only fires on attribute changes
          attributes: true, 
          attributeOldValue: true,

          // Only fires when the "style" attribute changes
          attributeFilter : ['style'],
        });
        return observer;
      },
    },
    height: String,
  },
  observers: [
    'heightUpdated(height)'
  ],
  mutated: function(mutations) {
    // Change this function if you want to listen for something else instead, this is fired on all "style" changes, and you can see the changes inside the "mutations" object it provides
    this.set('height', this.style.height);  
  },
  heightUpdated: function(height) {
    console.log('height', height);
  }
});

只要设置了this.style.height,它就会侦听,但是在调整元素大小时则不会。

希望突变观察者将使用css extension进行更新,以便为听取css样式更改提供更好的支持。在那之前,我不认为这是我能提出的最佳选择。