效果如下:可实现切换上下张图片,自动轮播,鼠标悬停轮播暂停
完整代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.wrapper {
width: 600px;
height: 350px;
margin: 0 auto;
overflow: hidden;
position: relative;
}
.contain img {
width: 600px;
height: 350px;
}
.contain {
width: 3000px; //包含图片的区域大,外面露的div小
height: 350px;
white-space: nowrap;
font-size: 0;
position: absolute;
left: 0;
}
.spots {
position: absolute;
left: 225px;
bottom: 10px;
}
.spots span {
display: inline-block;
width: 15px;
height: 15px;
border: 3px solid white;
border-radius: 50%;
margin-right: 8px;
}
a {
text-decoration: none;
font-size: 40px;
color: aliceblue;
position: absolute;
top: 155px;
}
a:nth-of-type(1) {
left: 15px;
}
a:nth-of-type(2) {
right: 15px;
}
.active {
background-color: lightgrey;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="contain">
<img src="imgs/1.png">
<img src="imgs/2.png">
<img src="imgs/3.png">
<img src="imgs/4.png">
<img src="imgs/5.png">
</div>
<div class="spots">
<span class="active"></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<a href="#"><</a>
<a href="#">></a>
</div>
</body>
<script type="text/javascript">
var _contain = document.querySelector(".contain");
var _wrapper = document.querySelector(".wrapper");
var _a1 = document.querySelector("a:nth-of-type(1)");
var _a2 = document.querySelector("a:nth-of-type(2)");
var _spots = document.querySelectorAll(".spots span");
var index = 0; //控制当前是第几张图片
// 下一张
function next_pic() {
if (_contain.offsetLeft <= -2400) {
_contain.style.left = 0;
} else {
_contain.style.left = (_contain.offsetLeft - 600) + "px";
console.log(_contain.offsetLeft);
}
index++;
if (index == 5) {
index = 0;
}
spots();
}
// 上一张
function pre_pic() {
if (_contain.offsetLeft >= 0) {
_contain.style.left = "-2400px";
} else {
_contain.style.left = (_contain.offsetLeft + 600) + "px";
console.log(_contain.offsetLeft);
}
index--;
if (index == -1) {
index = 4;
}
spots();
}
//小圆点颜色跟着变化
function spots() {
for (var i = 0; i < _spots.length; i++) {
if (i == index) {
_spots[i].className = "active";
} else {
_spots[i].className = "";
}
}
}
_a2.onclick = function() {
next_pic();
}
_a1.onclick = function() {
pre_pic();
}
//自动轮播
var id;
auto();
function auto() {
id = setInterval("next_pic()", 2000);
}
//鼠标悬浮轮播停止
_wrapper.onmouseover = function() {
clearInterval(id);
}
_wrapper.onmouseout = function() {
auto();
}
</script>
</html>