Javascript 实现图片无缝滚动

效果 : 鼠标移入图片 停止滚动, 鼠标移出自动滚动

可以调整向左或右方向滚动

复制代码 代码如下:


<style type="text/css">
            * {
                margin: 0;
                padding: 0;
            }
            #div1 {
                overflow: hidden;
                width: 712px;
                height: 108px;
                margin: 100px auto;
                position: relative;
                background: red;
            }
            #div1 ul {
                position: absolute;
                left: 0;
                top: 0;
            }
            #div1 ul li {
                float: left;
                width: 178px;
                height: 108px;
                list-style: none;
            }
        </style>

复制代码 代码如下:


<body>
        <a href="javascript:;">向左走</a>
        <a href="javascript:;">向右走</a>
        <div>
            <ul>
                <li>
                    <img src="https://www.jb51.net/img/无缝滚动/1.jpg" />
                </li>
                <li>
                    <img src="https://www.jb51.net/img/无缝滚动/2.jpg" />
                </li>
                <li>
                    <img src="https://www.jb51.net/img/无缝滚动/3.jpg" />
                </li>
                <li>
                    <img src="https://www.jb51.net/img/无缝滚动/4.jpg" />
                </li>
            </ul>
        </div>
    </body>

以上是一个简单的布局,下面是主要的Javascript 代码

复制代码 代码如下:


<script type="text/javascript">
            window.onload = function() {
                var oDiv = document.getElementById("div1");
                var oUl = oDiv.getElementsByTagName('ul')[0];
                var aLi = oUl.getElementsByTagName('li');
                var speed = 2;           
                oUl.innerHTML += oUl.innerHTML;
                oUl.style.width = aLi[0].offsetWidth * aLi.length + 'px';
                function move() {
                    if (oUl.offsetLeft < -oUl.offsetWidth / 2) {
                        oUl.style.left = '0';
                    }
                    if (oUl.offsetLeft > 0) {
                        oUl.style.left = -oUl.offsetWidth / 2 + 'px';
                    }
                    oUl.style.left = oUl.offsetLeft + speed + 'px';
                }
                var timer = setInterval(move, 30);
                oDiv.onmouseover = function() {
                    clearInterval(timer);
                };
                oDiv.onmouseout = function() {
                    timer = setInterval(move, 30);
                };
                document.getElementsByTagName('a')[0].onclick = function() {
                    speed = -2;
                };
                document.getElementsByTagName('a')[1].onclick = function() {
                    speed = 2;
                };
            }
        </script>

简单讲下思路:

首先设置ul 里面的图片一共有8张 oUl.innerHTML += oUl.innerHTML;

在 计算ul的宽度为 li的实际宽度*8

之后将 多余的内容隐藏

注意 : oUl.offsetLeft 肯定是负值

所以判断的时候不要把负号漏掉

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgxfpj.html