实现原理
1、设置一个最外层的可视区域,并且overflow:hidden
2、拷贝一份需要显示内容的DOM结构(为了不出现空白)
3、算出拷贝DOM之后内容的width(水平滚动),反正最外层溢出隐藏了
4、执行定时器,判断绝对定位left的值等于0或者长度最大值的时初始化位置(left的值为0或最大值取决于向左还是向右移动)
关键代码
<div class="content">
<ul>
<li><img src="https://www.lihuyong.com/wp-content/uploads/2019/05/demo.jpg"></li>
<li><img src="https://www.lihuyong.com/wp-content/uploads/2019/05/demo.jpg"></li>
<li><img src="https://www.lihuyong.com/wp-content/uploads/2019/05/demo.jpg"></li>
<li><img src="https://www.lihuyong.com/wp-content/uploads/2019/05/demo.jpg"></li>
<li><img src="https://www.lihuyong.com/wp-content/uploads/2019/05/demo.jpg"></li>
</ul>
</div>
*{
padding: 0;
margin: 0;
}
.content{
border: 1px solid #cccccc;
width: 600px;
height: 200px;
position: relative;
overflow: hidden;
}
.content ul{
overflow: hidden;
position:absolute;
width: 1000px;
left: 0;
top: 0;
_height:1px;
}
.content ul li{
float: left;
width: 400px;
list-style-type: none;
}
$(function(){
var oul = $('.content ul');
var oulHtml = oul.html();
oul.html(oulHtml+oulHtml)
var timeId = null;
var ali = $('.content ul li');
var aliWidth = ali.eq(0).width();
var aliSize = ali.size();
var ulWidth = aliWidth*aliSize;
oul.width(ulWidth);
var speed = 2; // -2 反方向滚动
function slider(){
if(oul.css('left')=='0px'){
oul.css('left',-ulWidth/2+'px');
}
oul.css('left','+='+speed+'px');
}
timeId = setInterval(slider,30);
$('.content').mouseover(function(){
clearInterval(timeId);
});
$('.content').mouseout(function(){
timeId = setInterval(slider,30);
});
});