使用HTML5+CSS3+JavaScript实现轮播图,可点击 切换图片,也可自动切换图片(0.5秒切换一次),图片自动衔接
代码实现:
<!DOCTYPE html>
<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;
}
.box {
width: 650px;
height: 360px;
border: 1px solid #000;
margin: 50px auto;
overflow: hidden;
position: relative;
}
.box ul {
list-style: none;
width: 5000px;
position: relative;
}
.box ul li {
float: left;
}
.box .last {
position: absolute;
left: 20px;
top: 50%;
margin-top: -25px;
width: 50px;
height: 50px;
background: url(images/icons.png) no-repeat -21px -94px;
}
.box .next {
position: absolute;
right: 20px;
top: 50%;
margin-top: -25px;
width: 50px;
height: 50px;
background: url(images/icons.png) no-repeat -21px -29px;
}
</style>
</head>
<body>
<div id="box" class="box">
<ul id="list">
<li><img src="images/0.jpg" alt=""></li>
<li><img src="images/1.jpg" alt=""></li>
<li><img src="images/2.jpg" alt=""></li>
<li><img src="images/3.jpg" alt=""></li>
<li><img src="images/4.jpg" alt=""></li>
</ul>
<a href="javascript:;" class="last" id="last"></a>
<a href="javascript:;" class="next" id="next"></a>
</div>
<script>
var box = document.getElementById('box');
var list = document.getElementById('list');
list.innerHTML += list.innerHTML;
var left = 0;
var idx = 0;
var timer;
move();
var lock = true;
function move() {
clearInterval(timer);
timer = setInterval(function () {
left -= 650;
if (left <= -3250) {
left = 0;
}
list.style.left = left + 'px';
}, 1000);
}
box.onmouseenter = function () {
clearInterval(timer);
next.onclick = function () {
if (!lock) return;
lock = false;
list.style.transition = 'left 0s ease 0s';
idx++;
if (idx > 4) {
setTimeout(function () {
list.style.transition = 'none';
list.style.left = 0;
idx = 0;
}, 500);
}
list.style.left = -idx * 650 + 'px';
// 函数节流
setTimeout(function () {
lock = true;
}, 500);
}
last.onclick = function () {
if (!lock) return;
lock = false;
if (idx == 0) {
list.style.transition = 'none';
list.style.left = -5 * 650 + 'px';
setTimeout(function () {
list.style.transition = 'left 0s ease 0s';
idx = 4;
list.style.left = -idx * 650 + 'px';
}, 0);
} else {
idx--;
list.style.left = -idx * 650 + 'px';
}
// 函数节流
setTimeout(function () {
lock = true;
}, 500);
}
}
box.onmouseleave = function () {
move();
}
</script>
</body>
</html>