最简单的方式实现轮播图
话不多说,直接粘代码
HTML片段
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>轮播图</title>
<link rel="stylesheet" href="./css/lunbotu.css">
<script src='../js/jQuery-3.4.1.min.js' ></script>
<script src='./js/lunbotu.js'></script>
</head>
<body>
<div id="container">
<div id="list">
<img src="./images/timg4.jfif" alt="">
<img src="./images/timg.jfif" alt="">
<img src="./images/timg1.jfif" alt="">
<img src="./images/timg2.jfif" alt="">
<img src="./images/timg3.jfif" alt="">
<img src="./images/timg4.jfif" alt="">
<img src="./images/timg.jfif" alt="">
</div>
<div id="buttons">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<a id="prev" class="arrow"><</a>
<a id="next" class="arrow">></a>
</div>
</body>
</html>
css片段
*{
margin: 0;
padding: 0;
}
body{
margin: 20px;
}
#container{
width: 500px;
height: 300px;
position: relative;
overflow: hidden;
}
#list{
position: absolute;
width: 3500px;
height: 300px;
margin-left: -500px;
}
img{
width: 500px;
height: 300px;
float: left;
}
#buttons{
width: 500px;
height: 300px;
position: absolute;
top: 270px;
text-align: center;
}
#buttons span{
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #bbb;
margin-left: 15px;
cursor: pointer;
}
#buttons .color{
background-color: red;
}
a{
text-decoration: none;
color: #fff;
font-size: 40px;
opacity: 0.3;
cursor: pointer;
}
#prev{
position: absolute;
top: 130px;
left: 10px;
z-index: 2;
}
a:hover{
color: #bbb;
opacity: 1;
}
#next{
position: absolute;
left: 465px;
top: 130px;
z-index: 2;
}
js片段
$(function(){
var $prev = $('#prev');
var $next = $('#next');
var n = 0;
$next.click(function(event) {
n++;
if(n>4){
$('#list').animate({left:-n*500},2000);
n=0;
$('#list').animate({left:-n*500},0);
}else{
$('#list').animate({left:-n*500},2000);
}
});
$prev.click(function(event) {
n--;
if(n<0){
$('#list').animate({left:-n*500},2000);
n=4;
$('#list').animate({left:-n*500},0);
}else{
$('#list').animate({left:-n*500},2000);
}
});
icoHove(n);
function dingshi(){
return stop=setInterval(function(){
n++;
if(n>4){
$('#list').animate({left:-n*500},2000);
n=0;
$('#list').animate({left:-n*500},0);
icoHove(n);
}else{
$('#list').animate({left:-n*500},2000);
icoHove(n);
}
},3000);
};
function icoHove(index){
$('span').eq(index).addClass('color').siblings().removeClass('color');
}
dingshi();
$('#container').hover(function(){
clearInterval(stop);
},function(){
dingshi();
});
var $arr = $('span');
$arr.each(function(index,item) {
//点击切换图片
$(item).click(function(event) {
$('#list').animate({left:-index*500},2000);
n = index;
icoHove(n);
});
});
})