实现原理:
1,布局要使用absolute,让每一项横排,最外层包住,里面再用一层包好每一项,这个宽度要算上每项的宽度总和;
2,向左轮播时,把最前面的一项放到后面;
3,向右轮播,把最后面的一项放到最前面。
具体实现看代码,感觉这个做法很方便!
<style type="text/css">
*{ margin:0;padding:0;}
.box{width: 500px;height: 400px;border: 1px solid #ddd;position: absolute;overflow: hidden; left: 50%;margin-left: -250px;margin-top: 50px;}
.swiper_item{width: 500px;height: 400px;float: left;text-align: center;line-height: 400px;display:inline-block;color: #fff;}
ul,li{list-style: none;}
.swiper{position: absolute; width:3500px;}
.item1{background-color: red;}
.item2{background-color: #000;}
.item3{background-color: #ddd;}
.item4{background-color: #888;}
.item5{background-color: blue;}
.btn_left{width: 50px;height: 50px;background-color: yellow;float: right;}
.btn_right{width: 50px;height: 50px;background-color: yellow;float: left;}
.btn{width: 500px;height: 50px;position: absolute;left: 50%;margin-left: -250px;margin-top: 150px;cursor: pointer;}
.num{width: 300px;height: 30px;position: fixed;left: 50%;margin-left: -80px;margin-top: 150px;cursor: pointer;margin-top: 400px;}
.num ul{list-style: none;}
.num li{float: left;width: 10px;height: 10px;background-color: #fff;border-radius: 50%;margin-left: 20px;}
</style>
<body>
<div class="box">
<ul class="swiper">
<li class="swiper_item item1">1</li>
<li class="swiper_item item2">2</li>
<li class="swiper_item item3">3</li>
<li class="swiper_item item4">4</li>
<li class="swiper_item item5">5</li>
</ul>
<div class="btn">
<div class="btn_left" ></div>
<div class="btn_right" ></div>
</div>
</div>
<div class="num">
<ul>
<li class="first_num"></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</body>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(function () {
$(".num .first_num").css("background-color","#000");
var timer=null;
$('.btn_left').click(function () { //点击向左轮播
swiperLeft()
})
$('.btn_right').click(function () { //点击向右轮播
$(".box ul").css('margin-left','-500px');
$(".box ul>li").eq(4).prependTo($(".box ul"));
$(".box ul").animate({'margin-left':"0px"},600);
changeColorRight()
})
})
//定时器,自动轮播
var timer = setInterval(function(){
swiperLeft()
},2000)
//鼠标放上去事件
$('.box').hover(function(){
clearInterval(timer);
},function(){
timer = setInterval(function(){
swiperLeft()
},2000)
})
//向左轮播
function swiperLeft(){
$(".box ul").animate({'margin-left':"-500px"},600, function () {
$(".box ul>li").eq(0).appendTo($(".box ul"));
$(".box ul").css('margin-left','0px');
});
changeColorLeft()
}
//向左轮播指示点颜色变化
function changeColorLeft(){
$(".num ul>li").css("background-color","");
var index = ($(".box ul>li").eq(1))[0].textContent -1
$(".num ul>li").eq(index)[0].style.backgroundColor = "#000"
}
//向右轮播指示点颜色变化
function changeColorRight(){
$(".num ul>li").css("background-color","");
var index = ($(".box ul>li").eq(0))[0].textContent - 1
$(".num ul>li").eq(index)[0].style.backgroundColor = "#000"
}
</script>
网友评论