js代码
<script type="text/javascript">
window.onload = function() {
//获取document
var timer;
var imgList = document.getElementById("imgList");
var imgArr = document.getElementsByTagName("img");
//计算长度
imgList.style.width = 112 * imgArr.length + "px";
//设置下标
var index = 0;
var allA = document.getElementsByTagName("a");
allA[index].style.backgroundColor = "black";
//定时器的应用
function getStyle(obj,name){
if(window.getComputedStyle){
return getComputedStyle(obj,null)[name];
}else{
return obj.currentStyle[name];
}
};
//函数定时器
function move(obj, attr, target, speed, callback) {
clearInterval(obj.timer);
var current = parseInt(getStyle(obj, attr));
if (current > target) {
speed = -speed;
}
obj.timer = setInterval(function() {
var oldValue = parseInt(getStyle(obj, attr));
var newValue = oldValue + speed;
if (speed < 0 && newValue < target || speed > 0 && newValue > target) {
newValue = target;
}
obj.style[attr] = newValue + "px";
if (newValue == target) {
clearInterval(obj.timer);
callback && callback();
}
}, 30)
};
for (var i = 0; i < allA.length; i++) {
allA[i].num = i;
allA[i].onclick = function() {
clearInterval(timer)
index = this.num;
setA();
move(imgList, "left", -111 * index, 20, function() {
autochange()
});
};
}
function setA() {
if (index >= imgArr.length - 1) {
index = 0;
// imgList.style.left = 0;
}
for (var i = 0; i < allA.length; i++) {
allA[i].style.backgroundColor = "";
}
allA[index].style.backgroundColor = "black";
};
function autochange() {
clearInterval(timer);
timer = setInterval(function() {
index++;
index %= imgArr.length;
move(imgList, "left", -112 * index, 500, function() {
});
setA();
}, 1000)
}
autochange();
}
</script>
css
<style>
* {
margin: 0;
padding: 0;
}
#outer {
width: 112px;
height: 112px;
margin: 10px auto;
padding: 2px;
background-color: yellowgreen;
overflow: hidden;
border-radius: 50%;
position: relative;
}
#imgList {
list-style: none;
position: absolute;
}
#imgList li {
margin: 0 1px;
float: left;
}
#navDiv {
margin: 0 auto;
width: 100px;
display: flex;
justify-content: space-between;
}
#navDiv a {
float: left;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: red;
opacity: 0.5;
}
#navDiv a:hover {
background-color: black;
}
</style>
body
<body>
<div id="outer">
<ul id="imgList">
<li><img src="./img/01.png" /></li>
<li><img src="./img/02.png" /></li>
<li><img src="./img/03.png" /></li>
<li><img src="./img/04.png" /></li>
<li><img src="./img/05.png" /></li>
<li><img src="./img/01.png" /></li>
</ul>
</div>
<div id="navDiv">
<a href="javascript:;"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
</div>
</body>