老师请检查,是否有待优化
来源:6-3 编写跑马灯轮播图特效
张小阳_
2022-07-14 10:01:39
<!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>carousel</title>
<style>
* {
padding: 0;
margin: 0;
text-decoration: none;
list-style: none;
}
.carousel {
width: 650px;
height: 360px;
margin: 0 auto;
position: relative;
overflow: hidden;
}
.carousel ul {
width: 4000px;
position: relative;
left: 0;
transition: left ease .5s;
}
.carousel ul li {
float: left;
}
.carousel a {
width: 50px;
height: 50px;
background-color: rgba(0, 0, 0, .3);
border-radius: 50%;
position: absolute;
top: 50%;
margin-top: -25px;
text-align: center;
line-height: 50px;
font-size: 25px;
}
.carousel .leftBtn {
left: 10px;
}
.carousel .rightBtn {
right: 10px;
}
</style>
</head>
<body>
<div class="carousel">
<ul id="list">
<li><img src="./images/0.jpg" alt=""></li>
<li><img src="./images/1.jpg" alt=""></li>
<li><img src="./images/2.jpg" alt=""></li>
<li><img src="./images/3.jpg" alt=""></li>
<li><img src="./images/4.jpg" alt=""></li>
</ul>
<a id="leftBtn" class="leftBtn" href="javascript:;"><</a>
<a id="rightBtn" class="rightBtn" href="javascript:;">></a>
</div>
<script>
var rightBtn = document.getElementById('rightBtn');
var list = document.getElementById('list');
// 克隆假图
var cloneImg = list.firstElementChild.cloneNode(true);
list.appendChild(cloneImg);
// 节流锁
var lock = true;
// 定义一个图片个数,从0开始计
var idx = 0;
rightBtn.onclick = function () {
if (!lock) return;
list.style.transition = 'left ease .5s';
idx++;
if (idx > 4) {
setTimeout(function () {
idx = 0;
list.style.left = -idx * 650 + 'px';
list.style.transition = 'none'; //去掉过渡动画
}, 500);
}
list.style.left = -idx * 650 + 'px';
lock = false;
setTimeout(function () {
lock = true;
}, 500);
};
// 绑定左键
var leftBtn = document.getElementById('leftBtn');
leftBtn.onclick = function () {
if (!lock) return;
if (idx <= 0) {
idx = 5;
list.style.left = -idx * 650 + 'px';
list.style.transition = 'none';
setTimeout(function () {
list.style.transition = 'left ease .5s';
idx = 4;
list.style.left = -idx * 650 + 'px';
}, 0);
} else {
idx--;
list.style.left = -idx * 650 + 'px';
}
lock = false;
setTimeout(function () {
lock = true;
}, 500);
};
</script>
</body>
</html>1回答
好帮手慕小李
2022-07-14
同学你好,这样就可以的很棒,这里的原生掌握了以后后续学习的知识点就更好理解了。
祝学习愉快!
相似问题