原理:子盒子是父盒子宽度的4倍,让父盒子产生scrollLeft值
每隔一段时间,让父盒子的scrollLeft加上图片的宽度
<style>
* {
padding: 0;
margin: 0;
}
#box {
width: 1400px;
height: 768px;
margin: 30px auto;
position: relative;
}
#fu {
width: 1400px;
height: 768px;
border: 1px solid black;
overflow: hidden;
}
#zi {
width: 8400px;
height: 768px;
}
#zi img {
width: 1400px;
height: 768px;
display: block;
float: left;
}
#dotted {
position: absolute;
left: 600px;
top: 745px;
list-style: none;
overflow: hidden;
}
#dotted li {
float: left;
width: 20px;
height: 20px;
border-radius: 50%;
border: 1px solid black;
opacity: 0.3;
background-color: #ccc;
margin-left: 5px;
}
#leftBtn,
#rightBtn {
position: absolute;
top: 384px;
width: 40px;
height: 60px;
background-color: black;
opacity: 0.5;
color: white;
text-align: center;
line-height: 60px;
font-size: 30px;
}
#leftBtn {
left: 0;
}
#rightBtn {
right: 0;
}
</style>
</head>
<body>
<div id="box">
<div id="fu">
<div id="zi">
<img src="../img/1.jpg" alt="">
<img src="../img/2.jpg" alt="">
<img src="../img/3.jpg" alt="">
<img src="../img/4.jpg" alt="">
<img src="../img/5.jpg" alt="">
<img src="../img/6.jpg" alt="">
</div>
</div>
<ul id="dotted">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<button id="leftBtn"><</button>
<button id="rightBtn">></button>
</div>
</body>
<script>
/*
原理:子盒子是父盒子宽度的4倍,让父盒子产生scrollLeft值
每隔一段时间,让父盒子的scrollLeft加上图片的宽度
*/
var fu = document.getElementById('fu')
var img = document.getElementById('zi').getElementsByTagName('img')[0]
//console.log(img);
var num = 0;
var clockTime;
zidong()
//封装一个自动轮播函数
function zidong() {
clockTime = setInterval(move, 2000)
}
function move() {
num++
if (num > 5) {
num = 0
}
if(num<0){
num = 5
}
// fu.scrollLeft = fu.scrollLeft + img.clientWidth
// fu.scrollLeft = img.clientWidth * num
liColor()
slowMove(fu.scrollLeft, img.clientWidth * num)
}
//封装一个缓慢轮播
function slowMove(start, end) {
var step = 0
var maxStep = 10
var huanStep = (end - start) / maxStep
var slowTime = setInterval(function () {
step++
if (step <= maxStep) {
fu.scrollLeft = fu.scrollLeft + huanStep
} else {
clearInterval(slowTime)
}
}, 50)
}
//小点轮播
var dotted = document.getElementById('dotted').getElementsByTagName('li')
for (var i = 0; i < dotted.length; i++) {
dotted[i].onmouseover = function () {
clearInterval(clockTime)
for (var j = 0; j < dotted.length; j++) {
if (dotted[j] == this) {
num = j
liColor()
slowMove(fu.scrollLeft, img.clientWidth * num)
}
}
zidong()
}
}
//左按钮
var leftBtn = document.getElementById('leftBtn')
leftBtn.onclick = function () {
clearInterval(clockTime)
num -= 2
move()
zidong()
}
//右按钮
var rightBtn = document.getElementById('rightBtn')
console.log(rightBtn);
rightBtn.onclick = function () {
clearInterval(clockTime)
move()
zidong()
}
//封装颜色
function liColor() {
for (var i = 0; i < dotted.length; i++) {
dotted[i].style.backgroundColor = ''
}
dotted[num].style.backgroundColor = 'black'
}
</script>