微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jQuery动画效果实现图片无缝连续滚动

本文实例介绍了jQuery动画效果实现图片无缝连续滚动的详细代码分享给大家供大家参考,具体内容如下

效果图如下:

一、HTML代码

rush:xhtml;">

1. id为container的div是最外层的包装,用来控制滚动区域显示的具体位置。 2. id为content的ul用来包装那些需要滚动的图片

3. li元素就是用来包装具体的图片

二、CSS代码

rush:css;"> *{margin: 0; padding: 0;}

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); 
}); 

};

1. 先通过each遍历所有的li元素,计算出它们宽度之和。 2. 拷贝一份图片到现有图片的后面,原理分析图的"图一"所示。

3. 设置6秒钟滚动完界面上面现有的图片,滚动完毕后,通过设置content的left值,将其整体拉回到初始状态,原理分析图的"图二"所示。然后递归调用run方法,完成无限滚动。

4. 当鼠标经过滚动区域的时候,动画立刻停止; 当鼠标离开的时候,动画继续执行。

关于动画继续执行的代码,如下图分析:

以上就是jQuery实现图片无缝连续滚动的代码,希望对大家的学习有所帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐