进度条思路:随着时间的改变,进度条的长度改变(兼容ie)
(1)定时器控制步长
(2)判断目标长度-现在长度是否小于步数长
(3)小于的话(不够跨一步了,会超出目标长度)执行计时器清除、现在长度强行为目标长度
(4)不小于就继续加步长
(1)HTML部分
<div class="box">
<p></p>
</div>
(2)CSS部分
.box {
width: 400px;
height: 100px;
border: 1px solid;
margin: 0 auto;
position: relative;
}
.box p {
margin: 0;
position: absolute;
height: 20px;
top: 40px;
left: 0px;
background: blue;
width: 0px;
}
(3)JS部分
// 兼容ie
function getStyle(ele, attr) { //元素 属性
if (ele.currentStyle) {
return ele.currentStyle[attr];
} else {
return getComputedStyle(ele)[attr];
}
}
var op = document.querySelector(".box p");
// 保存计时器返回值
var t;
var target = 400;
// 步长
var step = 3;
// 事件执行函数 用户点击页面执行
document.onclick = function() {
// 使用计时器之前 需要先清除!!(防止用户重复点击导致计时器累加 速度加快)
clearInterval(t);
//开启定时器 返回t
t = setInterval(function() {
// 获取当前值
var now = parseInt(getStyle(op, "width")); //调用兼容函数获得是带px的,只需要数据parseInt一下
if (target - now < step) {
// 不满足清除计时器并重新设置样式
clearInterval(t);
op.style.width = target + "px";
} else {
op.style.width = now + step + "px";
}
}, 30)
}