2014-11-01 57 views
0

我想知道如何觀察元素的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

不推薦... https://github.com/Polymer/observe-js/issues/ 49 – plalx 2014-11-01 20:13:48

+0

所以...這是一個非常糟糕的主意?我想我會找出其他的東西,因爲我不想放慢我的網頁。 – TheSeamau5 2014-11-01 20:22:16

+0

是的,這是一個壞主意;)你爲什麼要觀察元素的寬度?什麼過程可以改變它? – plalx 2014-11-01 20:36:09

回答

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

+0

我在ele.io上試過了,它不起作用。 https://ele.io/TheSeamau5/test-resize – TheSeamau5 2014-11-02 14:27:12

+0

@ TheSeamau5對不起我的壞。不應該讓它看起來是可複製的。特別是你有什麼問題實施它我可以幫你嗎? – Winchestro 2014-11-02 16:21:32

+1

非常感謝。我通過跟隨你的鏈接得到它的工作,但最終我發現了一種方法來做我想要的東西,而不必遵守寬度。這是一個非常奇怪的伎倆。 – TheSeamau5 2014-11-02 17:37:33