需求
頁面中一個小區域循環滾動展示通知(公告、新聞、活動、圖片等),並且鼠標hover時停止滾動並提示,鼠標離開后,繼續滾動。
效果圖
https://www.iguopin.com/index.php?m=&c=index&a=index
代碼實現
html
<div id="news">
<ul class="notices_box">
<li class="notice">
<a href="www.iguopin.com" target="_blank" title="1">1</a>
</li>
<li class="notice">
<a href="www.iguopin.com" target="_blank" title="2">2</a>
</li>
<li class="notice">
<a href="www.iguopin.com" target="_blank" title="3">3</a>
</li>
</ul>
</div>
css
#news {
height: 340px;
overflow: hidden;
}
.notices_box {
margin-left: 20px;
.notice {
margin-bottom: 8px;
list-style: disc;
font-size: 16px;
color: #e6a5ab;
a {
color: #000;
text-overflow: -o-ellipsis-lastline;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
line-height: 1.2;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
&:hover {
color: #c90808;
}
}
}
}
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能直接移動元素,就這些了。
