.box {
width: 0;
height: 50px;
line-height: 50px;
background-color: pink;
}
<div class="box">0%</div>
<button>开始</button>
<script>
var timer;
var box = document.getElementsByClassName("box")[0];
var btn = document.getElementsByTagName("button")[0];
console.log(box.offsetWidth);
btn.addEventListener("click",function(){
clearInterval(timer);
timer = setInterval(function(){
if(box.offsetWidth < 500) {
box.style.width = box.offsetWidth + 5 + "px";
box.innerHTML = box.offsetWidth / 5 + "%";
}else {
clearInterval(timer);
}
}, 16);
});
</script>踩的坑一:
box.style.width拿不到元素的width:原因在于,只有的元素的css是内嵌式,style.width才能拿到数据并返回xx px,否则返回空;内联式的时候通过offsetWidth可以拿到width(包括padding、border),返回的是数值;
style.width可以设置元素宽度,但offsetWidth不可以设置宽度;

京公网安备 11010502036488号