定位+计时器
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>轮播图</title>
<style>
#container{
width: 450px;
height: 270px;
margin: 0 auto;
margin-top: 100px;
position: relative;
overflow: hidden;
}
#pic{
width: 3150px;
height: 270px;
position: absolute;
z-index: 1;
}
/*图片大小*/
#pic img{
float: left;
width: 450px;
height: 270px;
}
#pre{
width: 37px;
height: 63px;
background: url(../img/L1.png);
position: absolute;
top: 120px;
left: 5px;
cursor: pointer;
z-index: 10;
}
#pre:hover{
background: url(../img/L2.png);
}
#next{
width: 37px;
height: 63px;
background: url(../img/R1.png);
position: absolute;
top: 120px;
right: 5px;
cursor: pointer;
z-index: 10;
}
#next:hover{
background: url(../img/R2.png);
}
#circle .first{
background-color: darkgrey;
}
#circle{
position: absolute;
top: 240px;
left: 130px;
z-index: 10;
height: 40px;
z-index: 2;
}
#circle span{
display: inline-block;
width: 20px;
height: 20px;
border-radius: 10px;
background-color: white;
margin-left: 8px;
}
</style>
</head>
<body>
<div id="container">
<div id="pic">
<img src="img/1.jpg" alt=""/>
<img src="img/2.jpg" alt=""/>
<img src="img/3.jpg" alt="3"/>
<img src="img/4.jpg" alt=""/>
<img src="img/5.jpg" alt=""/>
<img src="img/6.jpg" alt=""/>
<img src="img/7.jpg" alt=""/>
</div>
<div id="pre"></div>
<div id="next"></div>
<div id="circle">
<span class="first"></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
<script>
//索引值:控制全局
var index = 0;
var pic = document.getElementById("pic");
var pre = document.getElementById("pre");
var next = document.getElementById("next");
切换下一张图片
function next_pic () {
index++;
if(index == 7){
index = 0;
}
pic.style.left = -450*index + "px";
showCurrentCircle();
}
//切换上一张图片
function pre_pic () {
index--;
if(index == -1){
index = 6;
}
pic.style.left = -450*index + "px";
showCurrentCircle();
}
//点击下一张照片的事件
next.onclick = function () {
next_pic();
}
//点击上一张照片的事件
pre.onclick = function () {
pre_pic();
}
var timer = null;
//无限计时器,自动循环播放照片
function autoPlay () {
timer = setInterval(function () {
//调用
next_pic();
},2000);
}
//调用
autoPlay();
var container = document.getElementById("container");
//鼠标移入图片范围,移除计时器,图片自动轮播停止
container.onmouseenter = function () {
clearInterval(timer);
}
鼠标离开图片范围,计时器重启,图片自动轮播
container.onmouseleave = function () {
autoPlay();
}
var circle = document.getElementsByTagName("span");
//下方原点颜色跟随图片切换
function showCurrentCircle () {
//清除已经轮播过的圆点类
for(var i = 0; i < circle.length; i++){
circle[i].className = "";
console.log(i)
}
//再将原本的圆点类名赋给当前所轮播到的圆点
circle[index].className = "first";
}
//let:类似闭包效果,
for (let i = 0; i < circle.length; i++){
circle[i].onclick = function () {
pic.style.left = -450*i + "px";
index = i;
showCurrentCircle();
}
}
</script>
</body>
</html>