<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="../jquery.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 600px;
height: 400px;
margin: 0 auto;
position: relative;
}
li {
list-style: none;
}
ul>li {
position: absolute;
top: 0;
left: 0;
width: 600px;
height: 400px;
display: none;
}
span {
position: absolute;
top: 45%;
padding: 10px;
color: rgb(155, 153, 153);
background-color: rgba(197, 195, 195, 0.2);
}
.left {
left: 0px;
}
.right {
right: 0px;
}
.left:hover {
cursor: pointer;
background-color: rgba(97, 96, 96, 0.6);
}
.right:hover {
cursor: pointer;
background-color: rgba(102, 101, 101, 0.6);
}
ol {
position: absolute;
bottom: 20px;
left: 20px;
overflow: hidden;
}
ol>li {
float: left;
width: 10px;
height: 10px;
margin: 10px;
border-radius: 10px;
background-color: #eee;
}
ol>li:first-of-type {
background-color: black;
}
</style>
</head>
<body>
<div id="box">
<ul>
<li style="background-color: rgb(250, 36, 36);display:block"></li>
<li style="background-color: rgb(255, 238, 0);"></li>
<li style="background-color: rgb(43, 255, 0);"></li>
<li style="background-color: rgb(0, 38, 255);"></li>
<li style="background-color: rgb(255, 0, 234);"></li>
</ul>
<span class="left">上一张</span><span class="right">下一张</span>
<ol>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ol>
</div>
<script>
// 1.自动轮播
var i = 0; //全局声明一个i记录索引
var x = $("ul li").length
var timer = setInterval(function() {
i++
if(i == x){
i = 0;
}
$("ul li").eq(i).show().siblings().hide();
$("ol li").eq(i).css("backgroundColor","#000").siblings().css("backgroundColor","#eee")
}, 2000);
// 2.点击right实现图片下一张
$(".right").click(function(){
i++
if(i == x){
i = 0;
}
$("ul li").eq(i).show().siblings().hide();
$("ol li").eq(i).css("backgroundColor","#000").siblings().css("backgroundColor","#eee")
})
// 3. 点击left的时候 实现图片上一张
$(".left").click(function(){
i--
if(i < 0){
i = x - 1 ;
}
$("ul li").eq(i).show().siblings().hide();
$("ol li").eq(i).css("backgroundColor","#000").siblings().css("backgroundColor","#eee")
})
// 4. 当鼠标放到box的时候 自动轮播暂停 离开时继续
$("#box").hover(function(){
clearInterval(timer); // 移进去的时候暂停
},function(){
timer = setInterval(function() { // 移出去开始
i++
if(i == x){
i = 0;
}
$("ul li").eq(i).show().siblings().hide();
$("ol li").eq(i).css("backgroundColor","#000").siblings().css("backgroundColor","#eee")
}, 2000);
})
// 5. 点击下面小圆点的时候切换到对应的li的
$("ol li").click(function(){
i = $(this).index(); // 当我下面的小圆点点击的时候,索引等于上面li的索引,可以实现对应显示
$("ul li").eq(i).show().siblings().hide();
$("ol li").eq(i).css("backgroundColor","#000").siblings().css("backgroundColor","#eee")
})
</script>
</body>
</html>
这上面写的是很详细的步骤可以参考;
以下是一些重复性的代码,可以对其进行封装简化代码。。。