1. 程式人生 > 其它 >js實現css3的過渡,需要注意的一點(瀏覽器優化)

js實現css3的過渡,需要注意的一點(瀏覽器優化)

大部分瀏覽器對元素幾何改變時候的重排做了優化。據說是這樣子,一定時間內本應多次重排的改變,瀏覽器會hold住,僅一次重排。其中如果使用分離的一步處理過程,例如計時器,依然多次重排。例如,當我們應用transition動畫的時候,希望從0px變化到100px. 你如果如下程式碼:

dom.style.left = "0px";
dom.style.left = "100px";

元素是不會從0~100畫素動畫的,因為現代瀏覽器有自己的優化機制,它只會處理後面的dom.style.left = "100px",

可以通過訪問元素的OffsetHeight屬性,來讓起重繪,$.fn.redraw = function(){ $(this).each(function(){ var redraw = this.offsetHeight; });};

知道為啥這樣訪問offsetHeight可以實現功能嗎??原因很簡單,訪問元素的offsetHeight屬性會導致該元素的迴流,重新計算元素的位置。但是這樣實現動畫可能會造成效能問題。

之前轉載的一篇翻譯文章提到了 “影響迴流的因素”:

  1. 調整視窗大小(Resizing the window)
  2. 改變字型(Changing the font)
  3. 增加或者移除樣式表(Adding or removing a stylesheet)
  4. 內容變化,比如使用者在input框中輸入文字(Content changes, such as a user typing text in an input box)
  5. 啟用 CSS 偽類,比如 :hover (IE 中為兄弟結點偽類的啟用)(Activation of CSS pseudo classes such as :hover (in IE the activation of the pseudo class of a sibling))
  6. 操作 class 屬性(Manipulating the class attribute)
  7. 指令碼操作 DOM(A script manipulating the DOM)
  8. 計算 offsetWidth 和 offsetHeight 屬性(Calculating offsetWidth and offsetHeight)  根據此可以實現一個jquery外掛,讓元素迴流並重繪。ex. el.style.left=20px; a = el.offsetHeight;el.style.left=22px;
  9. 設定 style 屬性的值 (Setting a property of the style attribute)

還可以通過setTimeout來實現。

h.style.marginTop = '50px'
setTimeout(function(){
                h.style.marginTop = '150px'
            },130)

具體的過渡實現,可參考maccaw的部落格:http://blog.alexmaccaw.com/css-transitions