最简单的方法是动画使用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'将返回'“”' –