jQuery 实现列表自动滚动循环滚动显示新闻通知

需求

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

效果图

https://www.iguopin.com/index.php?m=&c=index&a=index

代码实现

html

        <div >
            <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能直接移动元素,就这些了。