jQuery 图片无缝滚动

2019-05-31  本文已影响0人  Astep

jQuery实现无缝图片滚动效果

<div class="bd">
   <ul class="picList">
       <li><img src="images/rh_1.jpg"></li>
       <li><img src="images/rh_2.jpg"></li>
       <li><img src="images/rh_3.jpg"></li>
    </ul>
</div>
<style>
.bd {
    position: relative;
    overflow: hidden;
    height: 320px;
}

.bd ul {
    position: absolute;
    top: 0;
    left: 0;
    zoom: 1;
}

.bd ul li {
    display: inline-flex;
}

.bd ul li img {
    padding-bottom: 10px;
}
</style>
<script type="text/javascript">
//如果要使一个元素运动起来,一般情况下这个元素需要具
//有position属性值可以是absolute/relative
       $(function() {
            let oul = $('.bd ul'),
            oulHtml = oul.html(),
            timeId = null,
            speed = 2;
            oul.html(oulHtml + oulHtml)
            let ali = $('.bd ul li'),
            aliHeight = ali.eq(0).height(),
            aliSize = ali.size(),
            ulHeight = aliHeight * aliSize;
            oul.height(ulHeight); //960px            

            function slider() {
                if (speed < 0) {
                    if (oul.css('top') == -ulHeight / 2 + 'px') {
                        oul.css('top', 0);
                    }
                    oul.css('top', '-=1px');
                }else if (speed > 0) {
                    if (oul.css('top') == '0px') {
                        oul.css('top', -ulHeight / 2 + 'px');
                    }
                    oul.css('top', '+=' + speed + 'px');
                }
            }

            // setInterval()函数的作用是:每隔一段时间,执行该函数里的代码
            timeId = setInterval(slider, 60);

            $('.bd').mouseover(function() {
                // clearInterval()函数的作用是用来清除定时器
                clearInterval(timeId);
            });

            $('.bd').mouseout(function() {
                timeId = setInterval(slider, 30);
            });

            $('.goLeft').click(function() {
                speed = -2;
            });

            $('.goRight').click(function() {
                speed = 2;
            });

        });
    </script>
上一篇 下一篇

猜你喜欢

热点阅读