本文实例介绍了jQuery动画效果实现图片无缝连续滚动的详细代码,分享给大家供大家参考,具体内容如下
效果图如下:
一、HTML代码
1. id为container的div是最外层的包装,用来控制滚动区域显示的具体位置。 2. id为content的ul用来包装那些需要滚动的图片。
3. li元素就是用来包装具体的图片。
二、CSS代码
img{
border:0;
}
container{
width:800px;
height: 130px;
<span style="white-space:pre"> margin:100px auto;
border:3px solid blue;
overflow: hidden;
position: relative;
}
container ul{
list-style: none;
width:10000px;
position: absolute;
}
container ul li{
float:left;
margin-right: 20px;
}
这里说明一点,ul 的 width为什么设置为10000px。 因为无缝连续滚动的实现原理,就是在现有显示图片的基础上克隆一份,并且拼接在显示图片的后面,但由于显示图片的总宽度是未知的,所以为了安全性,最好将ul的width宽度设置比较大些。
三、无缝连续滚动原理分析
四、JQuery实现代码
<div class="jb51code">
<pre class="brush:js;">
<script type="text/javascript">
/ window.onload比 $(function(){}) 加载的更晚一些,这样那些宽度的计算在Chrome中就可以准确计算了/
window.onload = function(){
/*计算<a href="https://www.jb51.cc/tag/yige/" target="_blank" class="keywords">一个</a>segment的宽度*/
var segmentWidth = 0;
$("#container #content li").each(function(){
segmentWidth+= $(this).outerWidth(true);
});
$("#container #content li").clone().appendTo($("#container #content"));
run(6000);
function run(interval){
$("#container #content").animate({"left":-segmentWidth},interval,"linear",function(){
$("#container #content").css("left",0);
run(6000);
});
}
$("#container").mouseenter(function(){
$("#container #content").stop();
}).mouseleave(function(){
var passedCourse = -parseInt($("#container #content").css("left"));
var time = 6000 * (1 - passedCourse/segmentWidth);
run(time);
});
};