原生JS实现无缝滚动

js代码:

var scroll = document.getElementById('scrollCont');
    var soul = scroll.getElementsByTagName('ul')[0];
    var aList = soul.getElementsByTagName('li');
    var prev = document.getElementById('prevs');
    var next = document.getElementById('nexts');
    var speed = 2;
    soul.innerHTML += soul.innerHTML;
    soul.style.width = aList[0].offsetWidth * aList.length + 'px';
    function carouselScroll() {
        
        if (soul.offsetLeft < -soul.offsetWidth / 2) {
            soul.style.left = '0';
        }
        if (soul.offsetLeft > 0) {
            soul.style.left = -soul.offsetWidth / 2 + 'px';
        }
        soul.style.left = soul.offsetLeft - speed + 'px';
    }
    
    var timer = setInterval(carouselScroll, 30);
    
    scroll.onmouseover = function () {
        clearInterval(timer)
    }
    scroll.onmouseout = function () {
        timer = setInterval(carouselScroll, 30);
    }

    prev.onclick=function (){
        speed = 2;
    }
    next.onclick=function (){
        speed = -2;
    }

html结构:

 

你可能感兴趣的:(javascript)