js 一页显示多张图无缝轮播
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
float: left;
}
#box {
width: 480px;
height: 80px;
border: 1px solid #000;
overflow: hidden;
position: relative;
margin: 100px auto;
}
#prev,
#next {
display: block;
width: 12px;
height: 12px;
border-radius: 50%;
background: #666;
color: #fff;
font-size: 25px;
text-align: center;
line-height: 12px;
position: absolute;
top: 50%;
margin-top: -6px;
cursor: pointer;
}
#prev {
left: 12px;
}
#next {
right: 12px;
}
#banner-box {
height: 100%;
position: absolute;
left: 0;
}
#banner-box li {
height: 100%;
width: 120px;
background: #ddd;
line-height: 80px;
text-align: center;
}
</style>
</head>
<body>
<div id="box">
<ul id="banner-box">
<!-- 6张 -->
<li>banner06</li>
<li>banner01</li>
<li>banner02</li>
<li>banner03</li>
<li>banner04</li>
<li>banner05</li>
<li>banner06</li>
<li>banner01</li>
<li>banner02</li>
<li>banner03</li>
<!-- 5张 -->
<!-- <li>banner05</li>
<li>banner01</li>
<li>banner02</li>
<li>banner03</li>
<li>banner04</li>
<li>banner05</li>
<li>banner01</li>
<li>banner02</li>
<li>banner03</li> -->
<!-- 4张 -->
<!-- <li>banner04</li>
<li>banner01</li>
<li>banner02</li>
<li>banner03</li>
<li>banner04</li>
<li>banner01</li>
<li>banner02</li>
<li>banner03</li> -->
</ul>
<span id="prev"></span>
<span id="next"></span>
</div>
</body>
</html>
<script>
window.onload = function() {
// 初始化轮播
let oBox = document.getElementById('box');
let oUl = document.getElementById('banner-box');
let oLi = oUl.children;
let prev = document.getElementById('prev');
let next = document.getElementById('next');
let timer = null;
let index = 1;
oUl.style.width = oLi[0].offsetWidth * oLi.length +'px';
oUl.style.left = '-120px';
//向前滚动
prev.onclick = function () {
index--;
move();
}
//向后滚动
next.onclick = function () {
index++;
move();
}
//自动轮播
function autoPlay () {
timer = setInterval (() => {
index++;
move();
}, 2000)
}
autoPlay();
oBox.onmouseover = function(){
clearInterval(timer);
}
oBox.onmouseout = autoPlay;
//运动函数
function move () {
if (index === (oLi.length - 3)) {
oUl.style.left = 0;
index = 1;
} else if (index === -1) {
oUl.style.left = -(oLi.length - 4) * oLi[0].offsetWidth + 'px';
index = oLi.length - 5;
}
animate(oUl, -index * oLi[0].offsetWidth);
}
function animate (obj, target){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
let speed = (target - parseInt(obj.style.left)) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (parseInt(obj.style.left) == target) {
clearInterval(obj.timer);
} else {
obj.style.left = parseInt(obj.style.left) + speed + 'px';
}
},30);
}
}
</script>```