js图片横向自动滚动

2022-01-25  本文已影响0人  shine001

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Title</title>

<style>
    * {
        margin: 0;
        padding: 0;
    }
    
    #div1 ul li {
        float: left;
        width: 200px;
        height: 150px;
        list-style: none
    }
    
    #div1 {
        width: 1000px;
        height: 160px;
        margin: 100px auto;
        position: relative;
        background: #fff;
        overflow: hidden;
        text-align: center;
    }
    
    #div1 span {
        text-align: center;
        line-height: 28px;
    }
    
    #div1 ul {
        position: absolute;
        left: 0;
        top: 0;
    }
</style>
<script>
    window.onload = function(ev) {
        var oDiv = document.getElementById("div1");
        var oul = oDiv.getElementsByTagName("ul")[0];
        var ali = oDiv.getElementsByTagName("li");
        var speed = 1;
        oul.innerHTML = 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 time = setInterval(move, 50);
        oDiv.onmouseover = function(ev2) {
            clearInterval(time);
        };
        oDiv.onmouseout = function(ev2) {
            time = setInterval(move, 50);
        };
        document.getElementsByTagName("a")[0].onclick = function() {
            speed = -2;
        };
        document.getElementsByTagName("a")[1].onclick = function() {
            speed = 2;
        }
    }
</script>

</head>

<body>
<a href="javascript:;">向左走</a>
<a href="javascript:;">向右走</a>

<div id="div1">
    <ul>
        <li><img src="./images/01.jpg" style="width: 180px;height:130px;" alt=""><span>asdasds</span></li>
        <li><img src="images/02.jpg" style="width: 180px;height:130px;" alt=""><span>asdasds</span></li>
        <li><img src="images/03.jpg" style="width: 180px;height:130px;" alt=""><span>asdasds</span></li>
        <li><img src="images/04.jpg" style="width: 180px;height:130px;" alt=""><span>asdasds</span></li>
        <li><img src="images/03.jpg" style="width: 180px;height:130px;" alt=""><span>asdasds</span></li>
        <li><img src="images/04.jpg" style="width: 180px;height:130px;" alt=""><span>asdasds</span></li>

    </ul>
</div>

</body>

</html>

上一篇下一篇

猜你喜欢

热点阅读