jQuery实现轮播图效果
前提是你下载了jquery的js文件,下载地址为http://jquery.com/download
如果没下也可以联网链接
准备5张图片命名为1到5.jpg
直接源代码使用
欢迎交流讨论
1.先看HTML和CSS代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片轮播效果</title>
<script src="js/jquery-3.6.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/图片轮播.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.box{
width: 500px;
height: 900px;
margin: 30px auto;
overflow: hidden;
position: relative;
}
#ulList{
list-style: none;
width: 1000%;
position: absolute;
}
#ulList li{
width: 500px;
height: 300px;
float: left;
}
.olList{
width: 300px;
height: 40px;
position: absolute;
left: 100px;
bottom: 30px;
list-style: none;
}
.olList li{
float: left;
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
margin: 0 10px;
background-color: #fff;
border-radius: 50%;
cursor: pointer;
}
.olList.now{
background-color: red;
color: #fff;
}
#left,#right{
position: absolute;
background: #0000FF;
color: white;
font-size: 30px;
font-weight: bold;
text-align: center;
}
#left{left: 0;top: 45%;}
#right{right: 0;top: 45%;}
</style>
</head>
<body>
<div class="box">
<ul id="ulList">
<li><img src="img/1.jpg" alt="" /></li>
<li><img src="img/2.jpg" alt="" /></li>
<li><img src="img/3.jpg" alt="" /></li>
<li><img src="img/4.jpg" alt="" /></li>
<li><img src="img/5.jpg" alt="" /></li>
</ul>
<ol class="olList">
<li class="now">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ol>
<div id="left"></div>
<div id="right"></div>
</div>
</body>
</html>
再来JavaScript代码
$(function(){
var nowIndex = 0;
var liNumber = $("#ulList li").length;
function change (index) {
var ulMove = index*500;//设置图片移动距离;
$("#ulList").animate({left:"-"+ulMove+"px"},500);
$(".olList").find("li").removeClass("now").eq(index).addClass("now");
}
var useInt = setInterval(function(){
if(nowIndex<liNumber-1){
nowIndex++;
}else{
nowIndex = 0;
}
change(nowIndex);
},2500);
function useIntAgain () {
useInt = setInterval(function(){
if(nowIndex<liNumber-1){
nowIndex++;
}else{
nowIndex = 0;
}
change(nowIndex);
},2500);}
$("#left").hover(function(){
clearInterval(useInt);
},function(){
useIntAgain();
});
$("#left").click(function(){
nowIndex = (nowIndex > 0)?(--nowIndex):(liNumber-1);
change(nowIndex);
})
$("#right").hover(function(){
clearInterval(useInt);
},function(){
useIntAgain();
});
$("#right").click(function(){
nowIndex = (nowIndex < liNumber-1)?(++nowIndex):0;
change(nowIndex);
});
$(".olList li").each(function(item){
$(this).hover(function(){
clearInterval(useInt);
nowIndex = item;
change(item);
},function(){
useIntAgain();
});
});
})