废话不多说,直接上源码:
html页面如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/轮播图.css"/>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="js/轮播图.js"></script>
<title>轮播图</title>
</head>
<body>
<div class="content">
<ul class="uItems">
<li><img src="img/1.jpg" /></li>
<li><img src="img/2.jpg" /></li>
<li><img src="img/3.jpg" /></li>
<li><img src="img/4.jpg" /></li>
<li><img src="img/5.jpg" /></li>
<li><img src="img/6.jpg" /></li>
</ul>
<div class="btn btnPrev"><</div>
<div class="btn btnNext">></div>
<ul class="uIndex">
<li class="bg">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</div>
</body>
</html>
css样式:
* {
padding: 0;
margin: 0;
moz-user-select: -moz-none;
-moz-user-select: none;
-o-user-select:none;
-khtml-user-select:none;
-webkit-user-select:none;
-ms-user-select:none;
user-select:none;
}
.content {
position: relative;
width: 512px;
height: 320px;
margin: 80px auto;
}
ul {
list-style-type: none;
}
.uIndex {
position: absolute;
bottom: 10px;
left: 135px;
}
.uItems li {
position: absolute;
}
.uItems li img {
width: 512px;
}
.btn {
width: 40px;
height: 60px;
text-align: center;
line-height: 60px;
background: #4d4d4d;
opacity: .8;
color: white;
font-size: 20px;
position: absolute;
}
.btnPrev {
top: 130px;
cursor: pointer;
}
.btnNext {
top: 130px;
right: 0;
cursor: pointer;
}
.uIndex li {
width: 30px;
height: 30px;
background: #11c1f3;
text-align: center;
line-height: 30px;
color: white;
border-radius: 50%;
float: left;
margin-right: 10px;
cursor: pointer;
}
.uIndex li.bg {
background: #e42012;
}
js代码:
var showIndex = 0;
var timer = null;
$(function(){
//显示第一张图片
$(".uItems li").not(":eq(0)").css("display","none");
//自动循环播放图片
startTimer();
//当鼠标悬浮在圆上时,关闭定时器,只显示当前图片。
$(".uIndex li").hover(function(){
clearInterval(timer);
showIndex = $(this).index();
showImg();
},
//鼠标移开时,又启动定时器。
function(){
startTimer();
});
//点击上一页图标时,关闭定时器,显示上一张图片,如果当前图片为第一张,则跳到最后一张图片的位置。
$(".btnPrev").click(function(){
clearInterval(timer);
if(showIndex==0){
showIndex = 6;
}
showIndex--;
showImg();
startTimer();
});
//点击下一页图标时,同理。
$(".btnNext").click(function(){
clearInterval(timer);
if(showIndex==5){
showIndex = -1;
}
showIndex++;
showImg();
startTimer();
});
})
//定时循环播放图片
function startTimer (){
timer = setInterval(function(){
showIndex++;
if(showIndex==6){
showIndex = 0;
}
showImg();
},2500);
}
//播放图片
function showImg(){
//暂停一下
$(".uItems li").stop(true,true)
//将所有图片隐藏
$(".uItems li").fadeOut(400);
//只显示当前showIndex的图片
$(".uItems li").eq(showIndex).fadeIn(400);
//移除所有圆的背景色
$(".uIndex li").removeClass("bg");
//给当前showIndex的圆设置背景色
$(".uIndex li").eq(showIndex).addClass("bg");
}