关于过渡效果失效的问题
老师好,这是我想的跑马灯轮播图,原理如下:
往左移动时,先过渡动画,然后移动节点
往右移动时,先移动节点,然后过渡动画
效果是能出来的,请老师点评一下,有没有什么不合理的地方或者需要改善的;
然后是标题中的问题,就是我发现,如果一个节点通过dom移动了之后,它就没有了过渡属性,虽说对我写代码来说是友好的,因为不需要想方设法的修改transition属性了,但是,理论上来说不应该,不知道哪里出了问题,请老师解惑。
代码如下(相关问题的代码我已经使用星号标记):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#carousel {
width: 800px;
height: 400px;
margin: 100px auto;
position: relative;
overflow: hidden;
}
#carousel .btn {
width: 40px;
height: 40px;
border-radius: 20px;
background-color: white;
text-align: center;
line-height: 40px;
position: absolute;
top: 50%;
margin-top: -20px;
}
#carousel .btn:hover {
cursor: pointer;
}
#carousel .btn.leftBtn {
left: 10px;
}
#carousel .btn.rightBtn {
right: 10px;
}
#carousel #imgBox div {
width: 800px;
height: 400px;
position: absolute;
left: 800px;
font-size: 100px;
text-align: center;
line-height: 400px;
transition: left 1s ease-in-out 0s;
}
#img1 {
background-color: yellowgreen;
}
#img2 {
background-color: saddlebrown;
}
#img3 {
background-color: violet;
}
#img4 {
background-color: orange;
}
#img5 {
background-color: rebeccapurple;
}
</style>
</head>
<body>
<div id="carousel">
<div id="imgBox">
<div id="img1" style="left:0px;">1</div>
<div id="img2">2</div>
<div id="img3">3</div>
<div id="img4">4</div>
<div id="img5">5</div>
</div>
<div class="leftBtn btn"></div>
<div class="rightBtn btn"></div>
</div>
<script>
var leftBtn = document.getElementsByClassName('leftBtn')[0];
var rightBtn = document.getElementsByClassName('rightBtn')[0];
var imgBox = document.getElementById('imgBox');
// children属性可以动态获取
var boxs = imgBox.children;
// 节流锁
var lock = false;
leftBtn.onclick = function () {
// 函数节流
if (lock) return;
// 先让前两张图往左移
boxs[0].style.left = '-800px';
boxs[1].style.left = '0px';
// 上锁
lock = true;
// 延时器,动画过渡之后,将第一个节点移动到最后,以此来循环
setTimeout(function () {
imgBox.appendChild(boxs[0]);
// ************此时设置left属性并不会有过渡效果*************
boxs[4].style.left = '800px';
// 解锁
lock = false;
}, 1000)
}
rightBtn.onclick = function () {
// 函数节流
if (lock) return;
// 先将最后一个节点移动到最前面,以此来循环
imgBox.insertBefore(boxs[4], boxs[0]);
// ************此时设置left属性并不会有过渡效果*************
boxs[0].style.left = '-800px';
// 不设置延时,box[0]的left会直接到0px,没有过渡效果
setTimeout(function () {
boxs[1].style.left = '800px';
boxs[0].style.left = '0px';
}, 0)
// 上锁
lock = true;
setTimeout(function () {
// 解锁
lock = false;
}, 1000)
}
</script>
</body>
</html>38
收起
正在回答 回答被采纳积分+1
1回答


恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星