运动插件
function animove(obj,distance,speed,callback) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
let step = (distance - obj.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if (obj.offsetLeft == distance) {
clearInterval(obj.timer);
if (callback) {
callback();
}
}
obj.style.left = obj.offsetLeft + step + 'px';
},speed)
}
CSS代码
* {
margin: 0;
padding: 0;
}
ul,li {
list-style: none;
}
.box {
width: 1226px;
height: 460px;
margin: 100px auto;
position: relative;
overflow: hidden;
}
.pic-box {
width: 4904px;
position: absolute;
}
.pic-box > li {
float: left;
}
.point {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
}
.point > li {
float: left;
width: 8px;
height: 8px;
border: 1px solid blueviolet;
margin: 0 4px;
border-radius: 50%;
}
.point > .active {
background-color: orange;
}
.left-btn,
.right-btn {
width: 50px;
height: 40px;
background-color: rgba(0,0,0,.5);
text-align: center;
line-height: 40px;
font-size: 20px;
color: white;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.left-btn {
left: 0;
}
.right-btn {
right: 0;
}
HTML代码
<div class="box">
<ul class="pic-box">
<li>
<img src="lb.webp" alt="">
</li>
<li>
<img src="lb2.webp" alt="">
</li>
<li>
<img src="pic3.jpg" alt="">
</li>
</ul>
<ul class="point">
</ul>
<div class="left-btn"><</div>
<div class="right-btn">></div>
</div>
<script src="运动插件.js"></script>
js代码
let picbox = document.querySelector('.pic-box');
let pic = document.querySelectorAll('.pic-box > li');
let point = document.querySelector('.point');
let leftbtn = document.querySelector('.left-btn');
let rightbtn = document.querySelector('.right-btn');
let carouselindex = 0;
for (let i = 0; i < pic.length; i ++) {
let pointli = document.createElement('li');
pointli.classList.add(i);
point.appendChild(pointli);
}
point.children[0].classList.add('active');
let kelon = picbox.children[0].cloneNode(true);
picbox.appendChild(kelon);
let pointli = document.getElementsByClassName('point')[0].getElementsByTagName('li');
function carousel(index) {
let distance = (-index * pic[0].offsetWidth);
animove(picbox,distance,10);
for (let i = 0; i < pointli.length; i ++) {
pointli[i].classList.remove('active');
}
if (index != pic.length) {
pointli[index].classList.add('active');
} else {
point.children[0].classList.add('active');
}
}
Array.prototype.forEach.call(pointli,function (item,index) {
item.addEventListener('click',function () {
carouselindex = index;
carousel(carouselindex);
})
});
rightbtn.addEventListener('click',function () {
carouselindex ++;
if (carouselindex > pic.length) {
picbox.style.left = "0px";
carouselindex = 1;
}
carousel(carouselindex);
});
leftbtn.addEventListener('click',function () {
carouselindex --;
if (carouselindex < 0) {
carouselindex = 2;
picbox.style.left = "-3678px";
}
carousel(carouselindex);
})