最簡單的方法是動畫使用jQuery .animate()
和閱讀從step:
參數回調當前寬度(閱讀文檔)的元素寬度...
使用CSS3過渡:
var $bar = $("#bar"),
$currWidth = $("#currWidth"),
itv = null;
$("#bar").on({
// START COUNTING THE WIDTH
// I used a custom "start" event cause currently (2016)
// Event.transitionstart is implemented only in IE10+, Edge
start : function(){
$(this).addClass("active");
itv = setInterval(function(){
$currWidth.text($bar[0].offsetWidth);
},10);
},
// STOP COUNTING THE WIDTH
transitionend : function() {
clearInterval(itv);
$currWidth.text("INTERVAL STOPPED");
}
});
$("#start").on("click", function(){ // CLICK JUST FOR DEMO,
// You need to place this trigger inside your inViewport method
// when the element enters the viewport
$bar.trigger("start"); // <<----------------
});
#bar{
height: 20px;
width:0;
background:red;
transition: 3s;
}
#bar.active{
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">ACTIVATE BAR</button><!-- TRIGGER BUTTON JUST FOR DEMO -->
width <span id="currWidth">0</span>
<div id="bar"></div>
當transitionstart
將所有主要的瀏覽器可以實現比代碼看起來很像:
var itv;
$("#bar").on({
transitionstart: function(){
itv = setInterval(function(){
console.log($bar[0].offsetWidth);
},10);
},
transitionend : clearInterval(itv)
});
$("#bar").addClass("active"); // place this call where needed
也許有一天,在另一個星系像transitionstep
一些事件可能是所有需要....
$("#bar").on("transitionstep", function(){ // :(
console.log(this.offsetWidth);
});
'document.getElementById(「yourDiv」)。width' ???此外,每20ms查詢一個元素的DOM是一個非常糟糕的主意。 –
再次...小心'Element.width'返回'undefined' ... 也有一段時間後停止那段時間會非常酷,你不覺得嗎? (不是說,至少在需要時啓動它會很好) –
**不,它不是固定的**。這是錯誤的:'style.width'將返回'「」' –