css
* {
padding: 0;
margin: 0;
}
#box {
margin: 100px auto;
width: 600px;
height: 400px;
position: relative;
}
#parent {
width: 600px;
height: 400px;
border: 1px solid red;
overflow: hidden;
}
#child {
float: left;
width: 2400px;
height: 400px;
}
#child img {
float: left;
width: 600px;
height: 400px;
display: block;
}
#ulList {
position: absolute;
left: 50px;
bottom: 20px;
}
#ulList ul {
list-style: none;
overflow: hidden;
}
ul li {
float: left;
padding: 10px;
border: 1px solid black;
border-right: 0;
}
ul li:last-child {
border-right: 1px solid black;
}
#leftBtn,
#rightBtn {
position: absolute;
top: 150px;
padding: 30px 10px;
border: 1px solid black;
}
#leftBtn {
left: 0;
}
#rightBtn {
right: 0;
}
html
<div id="box">
<div id="parent">
<div id="child">
<img src="./image/1.jpg" alt="">
<img src="./image/2.jpg" alt="">
<img src="./image/4.jpg" alt="">
<img src="./image/5.jpg" alt="">
</div>
</div>
<div id="ulList">
<ul>
<li style="background-color: red;">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
<div id="leftBtn">左</div>
<div id="rightBtn">右</div>
</div>
js
var parent = document.getElementById('parent')
var childImg = document.getElementById('child').getElementsByTagName('img')[0]
var ulList = document.getElementById('ulList').getElementsByTagName('li')
var leftBtn = document.getElementById('leftBtn')
var rightBtn = document.getElementById('rightBtn')
var num = 0
var timeAuto;
clock()
function clock() {
timeAuto = setInterval(autoMove, 2000)
}
function autoMove() {
num++
if (num > 3) {
num = 0
}
if (num < 0) {
num = 3
}
slowMove(parent.scrollLeft, childImg.clientWidth * num)
changeColor()
}
function slowMove(strat, end) {
var step = 0
var maxSetp = 10
var everyStep = (end - strat) / maxSetp
var timer = setInterval(function () {
step++
if (step <= maxSetp) {
parent.scrollLeft += everyStep
} else {
clearInterval(timer)
}
}, 50)
}
function changeColor() {
for (var i = 0; i < ulList.length; i++) {
ulList[i].style.backgroundColor = ''
}
ulList[num].style.backgroundColor = 'red'
}
for (let i = 0; i < ulList.length; i++) {
ulList[i].onclick = function () {
console.log('点击');
console.log(i);
clearInterval(timeAuto)
num = i
slowMove(parent.scrollLeft, childImg.clientWidth * num)
changeColor()
clock()
}
}
rightBtn.onclick = function () {
console.log('rightBtn');
clearInterval(timeAuto)
autoMove()
clock()
}
leftBtn.onclick = function () {
console.log('leftBtn');
clearInterval(timeAuto)
num -= 2
autoMove()
clock()
}