jQuery实现列表自动滚动循环滚动展示新闻

时间:2021-05-26

需要在页面中一个小的区域循环滚动展示新闻(公告、活动、图片等等),并且,鼠标悬停时停止滚动并提示,离开后,继续滚动。

效果图:

上干货

html:
复制代码 代码如下:
<div id="news">
<ul>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" title="aaaaaaaaaaaaaaa">aaaaaaaaaaaaaaa</a></li>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" title="bbbbbbbbbbbbbbb">bbbbbbbbbbbbbbb</a></li>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" title="ccccccccccccccc">ccccccccccccccc</a></li>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" title="ddddddddddddddd">ddddddddddddddd</a></li>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" title="eeeeeeeeeeeeeee">eeeeeeeeeeeeeee</a></li>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" title="fffffffffffffff">fffffffffffffff</a></li>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" title="ggggggggggggggg">ggggggggggggggg</a></li>
</ul>
</div>

css:
复制代码 代码如下:
ui,li {
list-style: none;
}
#news{
height: 75px;
overflow: hidden;
}

关键是js文件:
复制代码 代码如下:
$(function() {
var $this = $("#news");
var scrollTimer;
$this.hover(function() {
clearInterval(scrollTimer);
}, function() {
scrollTimer = setInterval(function() {
scrollNews($this);
}, 2000);
}).trigger("mouseleave");

function scrollNews(obj) {
var $self = obj.find("ul");
var lineHeight = $self.find("li:first").height();
$self.animate({
"marginTop": -lineHeight + "px"
}, 600, function() {
$self.css({
marginTop: 0
}).find("li:first").appendTo($self);
})
}
})

主要就是对hover、setInterval、clearInterval、animate这些方法以及marginTop属性(marginLeft、top、left等等)的理解和运用,需要注意的是,如果不加.trigger("mouseleave"),在网页初始化的时候列表不会滚动,还有appendTo能直接移动元素,就这些了。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章