欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js实现文字无限滚动轮播

程序员文章站 2022-04-04 20:57:21
...

html代码

<div>
	<ul id="ul1">
		<li>1111111111</li>
		<li>2222222222</li>
		<li>3333333333</li>
		<li>4444444444</li>
		<li>5555555555</li>
		<li>6666666666</li>
		<li>7777777777</li>
		<li>8888888888</li>
		<li>9999999999</li>
	</ul>
	<ul id="ul2"></ul>
</div>

css代码

*{
	padding:0;
	margin:0
}
div{
	height: 100px;
	width: 200px;
	border: 1px solid greenyellow;
	overflow: hidden;
}

js代码

var bigBox = document.querySelector('div')
var primary = document.querySelector('#ul1')
var copy = document.querySelector('#ul2')
var num = 0
copy.innerHTML = primary.innerHTML;
bigBox.scrollTop = 0;
var timer = setInterval(function () {
	if(bigBox.scrollTop >= primary.scrollHeight){
		bigBox.scrollTop = 0;
		num = 0
	}else{
		num++
		bigBox.scrollTop = num;
	}
},30);

添加鼠标移入移出事件

	bigBox.onmouseover = function(){
		clearInterval(timer);
	}
	bigBox.onmouseout = function(){
		timer = setInterval(function () {
			if(bigBox.scrollTop >= primary.scrollHeight){
				bigBox.scrollTop = 0;
				num = 0
			}else{
				num++
				bigBox.scrollTop = num;
			}
		},30);
	}

封装

// bigBox:外层的父级 primary:需要滚动的文字 copy:复制的容器 time:滚动速度
function scroll(bigBox,primary,copy,time) {
    var num = 0
    copy.innerHTML = primary.innerHTML;
    bigBox.scrollTop = 0;
    var timer = setInterval(function () {
        if(bigBox.scrollTop >= primary.scrollHeight){
            bigBox.scrollTop = 0;
            num = 0
        }else{
            num++
            bigBox.scrollTop = num;
        }
    },time);
    bigBox.onmouseover = function(){
        clearInterval(timer);
    }
    bigBox.onmouseout = function(){
        timer = setInterval(function () {
            if(bigBox.scrollTop >= primary.scrollHeight){
                bigBox.scrollTop = 0;
                num = 0
            }else{
                num++
                bigBox.scrollTop = num;
            }
        },time);
    }
}

调用

scroll(bigBox ,primary ,copy ,30)