html
js
<div class="container">
<div class="list" style='left:-500px;'>
<img src="img/6.png" alt="">
<img src="img/1.png" alt="">
<img src="img/2.png" alt="">
<img src="img/3.png" alt="">
<img src="img/4.png" alt="">
<img src="img/5.png" alt="">
<img src="img/6.png" alt="">
<img src="img/1.png" alt="">
</div>
<div class="buttons">
<span index='1' class="on"></span>
<span index='2'></span>
<span index='3'></span>
<span index='4'></span>
<span index='5'></span>
<span index='6'></span>
</div>
<a href="#" class="prev control">
<</a>
<a href="#" class="next control">></a>
</div>
css
* {
padding: 0;
margin: 0;
text-decoration: none;
}
.container {
position: relative;
width: 500px;
height: 500px;
border: 1px solid red;
overflow: hidden;
cursor: pointer;
}
.list {
position: absolute;
z-index: 1;
width: 4000px;
height: 500px;
}
.list img {
width: 500px;
height: 500px;
float: left;
}
.buttons {
position: absolute;
bottom: 20px;
z-index: 50;
height: 10px;
/*width: 100px;*/
left: 50%;
transform: translate(-50%, 0);
}
.buttons span {
margin: 0 8px;
border-radius: 50%;
height: 10px;
width: 10px;
background-color: #fff;
border: 1px solid #000;
float: left;
cursor: pointer;
/*display: inline-block;*/
}
.control {
position: absolute;
top: 50%;
z-index: 100;
width: 50px;
height: 50px;
font-size: 30px;
line-height: 50px;
text-align: center;
color: #fff;
background-color: rgba(0, 0, 0, .5);
cursor: pointer;
transform: translate(0, -50%);
}
.prev {
left: 10px;
}
.next {
right: 10px;
}
.buttons span.on{
background-color:orange;
}
js
var list = document.querySelector('.list'),
next = document.querySelector('.next'),
prev = document.querySelector('.prev');
var index = 1;
var buttons = document.querySelectorAll('span');
function init() {
buttons.forEach(function (item) {
if (item.className === 'on') {
item.className = '';
}
})
buttons[index - 1].className = 'on';
}
init();
function animate(offset) {
var newLeft = parseInt(getComputedStyle(list)['left']) + offset;
list.style.left = newLeft + 'px';
if (newLeft < -3500) {
list.style.left = '-500px';
}
if (newLeft > -500) {
list.style.left = '-3500px';
}
}
prev.onclick = function () {
index--;
if(index<1){
index = 6;
}
init();
animate(500);
}
next.onclick = function () {
index++;
if(index>6){
index = 1;
}
init();
animate(-500);
}
//自动切换
var timer;
function play() {
timer = setInterval(function () {
next.onclick();
}, 1000)
}
play();
//移入清除定时器
var container = document.querySelector('.container');
function stop() {
clearInterval(timer);
}
container.addEventListener('mouseover', function () {
stop();
})
//移出设置定时器
container.addEventListener('mouseout', function () {
play();
})
buttons.forEach(function(item){
item.addEventListener('click',function(){
var thisIndex =parseInt(item.getAttribute('index'));
var offset= 500*(index-thisIndex);
animate(offset);
index = thisIndex;
init();
})
})