走马灯特效

今天在项目中运用到了走马灯

自己写了下   也在网上查了一下  最后总结了一下

下面可以给大家举一个栗子:

html部分

<div class="container" id="container">
            <div class="text1" id="text1">
                <ul>
                    <li>我是第一个</li>
                    <li>我是第二个</li>
                    <li>我是第三个</li>
                    <li>我是第四个</li>
                    <li>我是第五个</li>
                    <li>我是第六个</li>
                </ul>
            </div>
            <div class="text2" id="text2"></div>
        </div>

css部分

* {
                margin: 0;
                padding: 0;
                font-size: 12px;
            }
            
            a {
                text-decoration: none;
            }
            
            ul,
            li {
                list-style: none;
            }
            
            .container {
                width: 600px;
                margin: 0 auto;
                height: 30px;
                line-height: 30px;
                background: plum;
                position: relative;
                overflow: hidden;
            }
            
            .container .text1 {
                width: 100%;
            }
            
            .container .text1 ul {
                width: 100%;
                height: 30px;
                display: flex;
            }
            
            .container .text1 ul li {
                font-size: 18px;
                color: white;
                width: 100px;
                text-align: center;
                font-weight: bold;
            }
            
            .container .text2 {
                height: 30px;
                width: 600px;
                line-height: 30px;
                position: absolute;
                left: 600px;
                top: 0;
            }
            
            .container .text2 ul {
                width: 100%;
                height: 30px;
                display: flex;
                
            }
            
            .container .text2 ul li {
                font-size: 18px;
                color: white;
                width: 100px;
                text-align: center;
                font-weight: bold;
            }

js 部分

var speed = 10; //数值越大速度越慢
        var container = document.getElementById("container")
        var text1 = document.getElementById("text1")
        var text2 = document.getElementById("text2")
        text2.innerHTML = text1.innerHTML;
        function Marquee() {
            if(text2.offsetWidth - container.scrollLeft <= 0) { //offsetWidth 是对象的可见宽度
                container.scrollLeft -= text1.offsetWidth //scrollWidth 是对象的实际内容的宽,不包边线宽度
            } else {
                container.scrollLeft++;
            }
        }
         setInterval(Marquee, speed)

简洁易懂   希望可以帮助到你 (开心)

posted @ 2019-04-12 18:19  wei小然  阅读(362)  评论(0编辑  收藏  举报