我有一个问题,我想点击第二个点触发定时器让绿色方块到-500px的位置然后清除定时器,但它只会移动到-494px,这导致定时器并没有停止运行
*{
margin: 0;
padding: 0;
}
.box{
width: 500px;
height: 300px;
border: 1px solid;
margin: auto;
position: relative;
}
.box ul{
margin: 0;
padding: 0;
width:400%;
list-style: none;
position: absolute;
}
.box ul li{
width: 500px;
height: 300px;
float:left;
}
.btn{
display: inline-block;
width: 40px;
height: 60px;
background-color: black;
position: absolute;
top: 50%;
margin-top: -30px;
}
.right{
left: 100%;
margin-left: -40px;
}
ol{
list-style: none;
padding: 0;
margin: 0 -60px;
position: absolute;
bottom: 5px;
left: 50%;
}
ol li{
width: 10px;
height: 10px;
background-color: #fff;
border-radius: 50%;
float: left;
margin:0px 10px;
}
div class="box">
<span class="btn"></span>
<span class="btn right"></span>
<ul>
<li style="background-color: red"></li>
<li style="background-color: green"></li>
</ul>
<!-- 圆点通过js动态生成-->
<ol></ol>
</div>
let li = document.querySelectorAll('li');
// 获取ul
let ul = document.querySelector('ul')
//获取按钮
let btn = document.querySelectorAll('span');
//获取轮播图小圆点
let ol = document.querySelector('ol');
//动态生成圆点
for(let i = 0; i < li.length; i++){
//创建节点
let dot = document.createElement('li');
ol.appendChild(dot);
// 给ol下li绑定点击事件并进行排他
dot.onclick = function () {
for(let i = 0; i < ol.children.length; i++){
ol.children[i].style.background = '';
}
this.style.background = 'black';
// 调用动画函数
move(ul,li[i].offsetWidth * -i);
console.log(li[i].offsetWidth * -i)
}
}
//封装一个动画函数,也可以用transition来实现动画效果
function move(obj,distance) {
clearInterval(obj.timer)
let step;
obj.timer = setInterval(function () {
step = (distance - obj.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step):Math.floor(step);
if(obj.offsetLeft == distance){
clearInterval(obj.timer)
}
obj.style.left = obj.offsetLeft + step + 'px';
console.log( obj.style.left,distance)
},15);
}