自动滚动轮播
2022-03-23 本文已影响0人
心存美好
自动滚动轮播
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="keywords" content="关键词">
<meta name="description" content="描述">
<meta name="author" content="">
<style>
body {
font-family: "Microsoft YaHei", serif;
}
body,
dl,
dd,
p,
h1,
h2,
h3,
h4,
h5,
h6 {
margin: 0;
}
ol,
ul,
li {
margin: 0;
padding: 0;
list-style: none;
}
img {
border: none;
}
#wrap {
position: relative;
width: 780px;
height: 380px;
margin: 50px auto 0;
user-select: none;
}
#img {
overflow: hidden;
position: relative;
width: 100%;
height: 330px;
}
#img ul {
position: absolute;
top: 0;
left: 0;
width: 10000%;
height: 100%;
transition: left .3s;
}
#img ul.on {
transition: left .0s;
}
#img li {
float: left;
width: 1%;
height: 100%;
}
#tab {
overflow: hidden;
width: 100%;
height: 50px;
}
#tab ul {
width: 200%;
height: 100%;
}
#tab li {
float: left;
width: 10%;
height: 50px;
line-height: 50px;
text-align: center;
background-color: #000;
font-size: 12px;
color: #eee;
cursor: pointer;
}
#tab li.active {
background-color: #303030;
color: #e9c06c;
}
#arrow div {
position: absolute;
top: 50%;
width: 40px;
height: 60px;
margin-top: -30px;
line-height: 60px;
text-align: center;
font-size: 12px;
background-color: #000;
color: #fff;
cursor: pointer;
}
#arrow div.last {
left: 0;
}
#arrow div.next {
right: 0;
}
</style>
</head>
<body>
<div id="wrap">
<!--图片部分对应的布局-->
<div id="img">
<ul>
<li>
<a href=""><img src="img/1.jpg" alt=""></a>
</li>
<!-- num +1 -->
<li>
<a href=""><img src="img/2.jpg" alt=""></a>
</li>
<li>
<a href=""><img src="img/3.jpg" alt=""></a>
</li>
<li>
<a href=""><img src="img/4.jpg" alt=""></a>
</li>
<li>
<a href=""><img src="img/5.jpg" alt=""></a>
</li>
</ul>
</div>
<!--按钮部分对应的布局-->
<div id="tab">
<ul>
<li class="active">开黑吗</li>
<li>我亚索贼6</li>
<li>只要我E的够快</li>
<li>队友的问号</li>
<li>就跟不上我</li>
</ul>
</div>
<!-- 左右按钮 -->
<div id="arrow">
<div class="last">
< </div>
<div class="next">
>
</div>
</div>
</div>
<script>
// 获取元素
let oUl = document.querySelector('#img ul')
let aTapLi = [...document.querySelectorAll('#tab li')];
// 信号量
let wid = 780, idx = 0; len = aTapLi.length;
//批量绑定事件
aTapLi.forEach((oLi, index) => {
oLi.onclick = function () {
if (index == idx) return;//点击索引与初始显示所以一样,就要节流
change(index)
}
})
//开启定时器执行这个函数就是自动滚动轮播
function change(index) {
aTapLi[idx].className = '';
idx = index;
aTapLi[idx].className = 'active'
oUl.style.left = -index * wid + 'px';
}
//定时器
setInterval(function () {
index = idx;
index++;
if (index >= len) index = 0;
change(index);
}, 1000)
</script>
</body>
</html>