js实现自动滚动

js实现自动滚动,再也不用求swiper组件啦

标签

<div id="box">
	<div id="content">需要自动滚动的内容div>
	<div id="copy">div>
div>

样式

#box{
	width: 100%;
	height: 100%;
	overflow-y: auto;
}

自动滚动代码

function scroll(bigBox, primary, copy, time) {
  if (bigBox.clientHeight >= primary.scrollHeight) {
      // 不需要滚动
      return;
  }
  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 () {
  	// 接着鼠标移出的地方
  	num = bigBox.scrollTop >= primary.scrollHeight ? bigBox.scrollTop - primary.scrollHeight : bigBox.scrollTop; 
    bigBox.scrollTop = num;
    timer = setInterval(function () {
      if (bigBox.scrollTop >= primary.scrollHeight) {
        bigBox.scrollTop = 0;
        num = 0;
      } else {
        num++;
        bigBox.scrollTop = num;
      }
    }, time);
  };
}

useEffect(() => {
  var bigBox= document.querySelector('#box');
  var primary = document.querySelector('#content');
  var copy = document.querySelector('#copy');
  scroll(bigBox, primary, copy, 30);
}, []);

你可能感兴趣的:(javascript,前端,开发语言)