轮播图案例
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
position: relative;
}
#parent {
width: 600px;
height: 400px;
margin: 100px auto;
border: 1px solid red;
overflow: hidden;
}
#child {
width: 2400px;
height: 400px;
overflow: hidden;
}
#child img {
width: 600px;
height: 400px;
display: block;
float: left;
}
#ul {
position: absolute;
bottom: 15%;
left: 35%;
}
ul {
list-style: none;
overflow: hidden;
}
ul li {
float: left;
border: 1px solid red;
padding: 10px;
color: wheat;
}
#leftBtn,
#rightBtn {
color: wheat;
position: absolute;
top: 180px;
border: 1px solid red;
padding: 20px 10px;
}
#leftBtn {
left: 30.5%;
}
#rightBtn {
left: 67%;
}
</style>
</head>
<body>
<div class="box">
<div id="parent">
<div id="child">
<img src="https://img1.baidu.com/it/u=805103204,11749913&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1200"
alt="">
<img src="https://img1.baidu.com/it/u=3518673092,2032183538&fm=253&fmt=auto&app=138&f=JPEG?w=781&h=500"
alt="">
<img src="https://img0.baidu.com/it/u=1732529670,559512920&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500"
alt="">
<img src="https://img0.baidu.com/it/u=1033018635,7901815&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500"
alt="">
</div>
</div>
<div id="ul">
<ul>
<li style="background-color: brown;">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
<div id="leftBtn">
左
</div>
<div id="rightBtn">
右
</div>
</div>
</body>
var parent = document.getElementById('parent')
var rightBtn = document.getElementById('rightBtn')
var leftBtn = document.getElementById('leftBtn')
var childImg = document.getElementById('child').getElementsByTagName('img')[0]
var liList = document.getElementById('ul').getElementsByTagName('li')
var num = 0
var moveTimer;
time()
function time() {
moveTimer = setInterval(imgMove, 2000)
}
function imgMove() {
num++
if (num > 3) {
num = 0
parent.scrollLeft = 0
}
if (num < 0) {
num = 3
parent.scrollLeft = 1800
}
slowScroll(parent.scrollLeft, childImg.clientWidth * num)
changeClor()
}
function slowScroll(start, end) {
var step = 0
var maxStep = 5
var every = (end - start) / maxStep
var timer = setInterval(function () {
step++
if (step > maxStep) {
clearInterval(timer)
} else {
parent.scrollLeft += every
}
}, 50)
}
function changeClor() {
for (var i = 0; i < liList.length; i++) {
liList[i].style.backgroundColor = ''
}
liList[num].style.backgroundColor = 'brown'
}
for (let i = 0; i < liList.length; i++) {
liList[i].onclick = function () {
console.log(i);
num = i
clearInterval(moveTimer)
slowScroll(parent.scrollLeft, childImg.clientWidth * num)
changeClor()
time()
}
}
rightBtn.onclick = function () {
clearInterval(moveTimer)
imgMove()
time()
}
leftBtn.onclick = function () {
clearInterval(moveTimer)
num -= 2
imgMove()
time()
}