<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>轮播图</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<style>
* {
margin: 0px;
padding: 0px;
}
.banner {
width: 600px;
margin: auto;
border: 10px solid greenyellow;
height: 350px;
position: relative;
overflow: hidden;
}
.imgList {
list-style: none;
/* width: 2480px; */
position: absolute;
/* left:-620px; */
}
.imgList img {
width: 600px;
height: 350px;
}
.imgList li {
float: left;
margin-right: 20px;
}
.circle {
position: absolute;
bottom: 15px;
left: 50%;
transform: translateX(-50%);
}
.circle a {
width: 15px;
height: 15px;
background: yellow;
display: block;
border-radius: 50%;
opacity: .5;
float: left;
margin-right: 5px;
cursor: pointer;
}
.circle a.hover {
background: black;
opacity: .8;
}
</style>
</head>
<body>
<div class="banner">
<ul class="imgList">
<li><img src="../1.png" alt=""></li>
<li><img src="../2.jpg" alt=""></li>
<li><img src="../3.jpg" alt=""></li>
<li><img src="../4.jpg" alt=""></li>
</ul>
<div class="circle">
<!-- <a href=""></a>
<a href=""></a>
<a href=""></a>
<a href=""></a> -->
</div>
</div>
<script>
window.onload = function () {
var imgList = document.querySelector('.imgList');
var circle = document.querySelector('.circle');
var thisIndex = 0;
var imgListLi = imgList.children;
var circleA = circle.children;
var flag = true;
imgList.style.width = imgList.children.length * 620 + 'px';
for (var i = 0; i < imgList.children.length; i++) {
var aNode = document.createElement('a');
aNode.setAttribute('index', i); //设置自定义属性
if (i == 0) {
aNode.className = 'hover';
}
circle.appendChild(aNode);
}
circle.addEventListener('click', function (e) {
if (flag) {
flag = false;
// console.log(e.target);
if (e.target.nodeName != 'A') {
return false;
}
thisIndex = e.target.getAttribute('index');
// imgList.style.left = -thisIndex * 620 + 'px';
slow(imgList, -thisIndex * 620, function () {
flag = true;
});
circleChange();
}
})
function antoChange() {
setInterval(function () {
if (flag) {
flag = false;
if (thisIndex >= circleA.length) {
thisIndex = 0;
}
slow(imgList, -thisIndex * 620, function () {
flag = true;
});
circleChange();
thisIndex++;
}
}, 3000);
}
function circleChange() {
for (var i = 0; i < circleA.length; i++) {
circleA[i].className = '';
}
circleA[thisIndex].className = 'hover';
}
function slow(obj, target, callback) {
obj.myInter = setInterval(function () {
var offsetLeft = obj.offsetLeft;
var num = (target - offsetLeft) / 10;
num > 0 ? num = Math.ceil(num) : num = Math.floor(num);
if (offsetLeft == target) {
clearInterval(obj.myInter);
callback && callback();
} else {
obj.style.left = offsetLeft + num + 'px';
}
}, 10)
}
antoChange();
}
</script>
</body>
</html>
js原生轮播图完整代码拿过来就用
最新推荐文章于 2024-04-05 18:17:54 发布