初级jQuery做的图片轮播
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片轮播</title>
</head>
<body>
<div class="container">
<div class="box">
<img src="1.jpg">
<img src="2.jpg">
<img src="3.jpg">
<img src="4.jpg">
</div>
<div class="circle">
<b class="now"></b>
<b></b>
<b></b>
<b></b>
</div>
<!-- <="<" >=">" -->
<div class="btn left"> < </div>
<div class="btn right"> > </div>
</div>
</body>
</html>
css代码:
*{
margin: 0;
padding: 0;
}
.container {
/* position: relative; */
width: 100%;
height: 100%;
/* background-color: #000; */
}
.box,
.box img {
width: 100%;
height: 100%;
position: absolute;
}
.circle {
position: absolute;
width: 200px;
height: 15px;
bottom: 15px;
left: 50%;
margin-left: -100px;
text-align: center;
/* 设置光标效果 */
cursor: pointer;
}
.circle b {
display: inline-block;
width: 15px;
height: 15px;
background-color: #000;
border-radius: 50%;
margin: 5px;
}
.circle .now {
background-color: white;
}
.btn {
position: absolute;
top: 50%;
width: 40px;
height: 60px;
margin-top: -25px;
background-color: white;
opacity: 0.5;
text-align: center;
line-height: 60px;
font-size: 60px;
cursor: pointer;
}
.left {
left: 10px;
}
.right {
right: 10px;
}
JavaScript代码:
<script src="jquery.js"></script>
<script>
// i表示当前图片的索引
var i = 0;
var timer;
$(function(){
// siblings() 找出当前元素的所有同辈元素
$("img").eq(0).show().siblings().hide();
start();
$("b").hover(function(){
console.log("执行了");
clearInterval(timer);
i = $(this).index();
change();
}, function(){
start();
});
$(".left").click(function(){
i--;
if(i == -1){
i = 3;
}
change();
});
$(".right").click(function(){
i++;
if(i == 4){
i = 0;
}
change();
});
});
// 自动轮播
function start(){
timer = setInterval(function(){
i++;
if(i == 4){
i = 0;
}
change();
}, 5000);
}
function change(){
$("img").eq(i).fadeIn(1000).siblings().fadeOut(1000);
$("b").eq(i).addClass("now").siblings().removeClass("now");
}
</script>
效果图
点击左右两边的箭头图片分别左右滑动;
当鼠标悬浮在底部的小圆圈上时会显示对应的图片;
此效果在网站首页宣传图处最常见。