首页 > 代码库 > 使用jQuery实现简单的图片轮播

使用jQuery实现简单的图片轮播

<!--先把样式定义好-->

<style>
*{
box-sizing: border-box;
margin: 0px;
padding: 0px;
}
body{
background-color: lightgray;
}
.MarginDiv{
border: 1px solid green;
width: 1320px;
height: 245px;
overflow: hidden;
margin: 0px auto;
position: relative;
}
.MarginDiv button{
position: absolute;
width: 30px;
line-height: 80px;
top: 80px;
background-color: rgba(0,0,0,.5);
border: 1px solid white;
color: white;
font-weight: 900;
font-size: 22px;
z-index: 99;
}
.MarginDiv button:first-child{left: 0px;}
.MarginDiv button:last-child{right: 0px;}
.MarginDiv ul{
list-style: none;
}
.MarginDiv ul li{
float: left;
width: 420px;
height: 240px;
/*border: 1px solid green;*/
margin: 0px 10px;
padding-top:10px ;
background-color: whitesmoke;
}
.MarginDiv ul:after{
display: block;
clear: both;
content: "";
}
.MarginDiv img {
width: 400px;
height: 220px;
display: block;
margin:0px auto;
}
</style>

<!--设置布局-->

<div class="MarginDiv">
<ul>
<li><a href="javascript:;"><img src="http://www.mamicode.com/img/1.jpg"></a></li>
<li><a href="javascript:;"><img src="http://www.mamicode.com/img/2.jpg"></a></li>
<li><a href="javascript:;"><img src="http://www.mamicode.com/img/3.jpg"></a></li>
<li><a href="javascript:;"><img src="http://www.mamicode.com/img/4.jpg"></a></li>
<li><a href="javascript:;"><img src="http://www.mamicode.com/img/5.jpg"></a></li>
<li><a href="javascript:;"><img src="http://www.mamicode.com/img/6.jpg"></a></li>
<li><a href="javascript:;"><img src="http://www.mamicode.com/img/7.jpg"></a></li>
</ul>
<button>&lt;</button>
<button>&gt;</button>
</div>

 

<!--引入jQuery文件-->

<script type="text/javascript" src="http://www.mamicode.com/js/jquery-1.11.0.js" ></script>

<script>
$(function(){
var ul = $(‘.MarginDiv ul‘);
var lis = $(‘.MarginDiv ul‘).find(‘li‘);
//获取长度
lis.size();
//获取li的宽度(含有内外边距);
lis.outerWidth(true);
//动态计算ul的宽度
$(‘.MarginDiv ul‘).width(lis.size()*lis.outerWidth(true))
//选出按钮
var LeftBtn = $(‘.MarginDiv button‘).first(),
RightBtn = $(‘.MarginDiv button‘).last();

//设置定时器,当鼠标移入后,定时器关闭
var time = setInterval(MoveLeft,1500);
RightBtn,LeftBtn,ul.hover(function(){
clearInterval(time);
},function(){
time = setInterval(MoveLeft,1500)
});

//绑定按钮事件,调用函数
LeftBtn.on(‘click‘,function(){
MoveLeft();
});
RightBtn.on(‘click‘,function(){
MoveRight();
});
//位移设置
function MoveLeft(){
$(‘.MarginDiv ul li‘).first().animate({‘marginLeft‘:‘-440px‘},500,function(){
$(this).css(‘marginLeft‘,‘10px‘).appendTo(ul);
console.log(this);
});
}
function MoveRight(){
$(‘.MarginDiv ul li‘).last().prependTo(ul);
$(‘.MarginDiv ul li‘).first().css(‘marginLeft‘,‘-440px‘).animate({‘marginLeft‘:‘10px‘},500,function(){
console.log(this);
});
}

})

</script>

//这是效果图

技术分享

使用jQuery实现简单的图片轮播