css
* {
padding: 0;
margin: 0;
}
ul li {
list-style: none;
}
.conatiner {
width: 600px;
height: 300px;
margin: 0 auto;
overflow: hidden;
position: relative;
}
.content {
width: 2400px;
height: 300px;
}
.content li {
float: left;
width: 600px;
height: 300px;
text-align: center;
line-height: 300px;
font-size: 50px;
color: #fff;
display: none;
}
.active {
display: block !important;
}
.spans {
position: absolute;
bottom: 10px;
right: 0;
left: 0;
margin: 0 auto;
width: 120px;
}
.spans span {
width: 20px;
height: 20px;
background-color: orange;
border-radius: 50%;
float: left;
margin-right: 10px;
}
.spans span.on {
background-color: #fff;
}
.leftBtn {
left: 10px;
background-color: rgba(0, 0, 0, .6);
position: absolute;
top: 37%;
border-radius: 5px;
line-height: 60px;
text-align: center;
width: 35px;
height: 60px;
display: block;
color: #fff;
font-weight: 700;
}
.rightBtn {
background-color: rgba(0, 0, 0, .6);
right: 10px;
position: absolute;
top: 37%;
border-radius: 5px;
line-height: 60px;
text-align: center;
width: 35px;
height: 60px;
display: block;
color: #fff;
font-weight: 700;
}
.leftBtn:hover {
background-color: #000;
}
.rightBtn:hover {
background-color: #000;
}
html
<div class="conatiner">
<ul class="content">
<li style="background-color: aqua;" class="active">1</li>
<li style="background-color: blueviolet;">2</li>
<li style="background-color: cadetblue;">3</li>
<li style="background-color: salmon;">4</li>
</ul>
<div class="spans">
<span class="on"></span>
<span></span>
<span></span>
<span></span>
</div>
<span class="leftBtn"><</span>
<span class="rightBtn">></span>
</div>
js
var content = document.getElementsByClassName('content')[0]
var lis = content.getElementsByTagName('li')
var index = 0
var spans = document.getElementsByClassName('spans')[0]
var spanlist = spans.getElementsByTagName('span')
var left = document.getElementsByClassName('leftBtn')[0]
var right = document.getElementsByClassName('rightBtn')[0]
var conatiner = document.getElementsByClassName('conatiner')[0]
timer = setInterval(autoPlay, 2000)
function autoPlay() {
index++;
if (index >= lis.length) {
index = 0
}
changeLis(index)
}
function changeLis(currentIndex) {
for (var i = 0; i < lis.length; i++) {
lis[i].className = ""
}
for (var j = 0; j < spanlist.length; j++) {
spanlist[j].className = ''
}
lis[currentIndex].className = 'active'
spanlist[currentIndex].className = 'on'
content.style.marinRight = -600 * currentIndex + 'px'
index = currentIndex
}
conatiner.onmouseover = function () {
clearInterval(timer)
}
conatiner.onmouseout = function () {
timer = setInterval(autoPlay, 2000)
}
left.addEventListener('click', function () {
if (index <= 0) {
index = lis.length
}
index--
changeLis(index)
clearInterval(timer)
})
right.addEventListener('click', function () {
index++;
if (index >= lis.length) {
index = 0
}
changeLis(index)
clearInterval(timer)
})
效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0209cc89be541002cc4aa4a7395a3432.gif)