js横向或竖向无缝循环滚动

由 夕空 撰写于  2024年3月20日
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>横向或竖向无缝滚动</title>
<style>
#scroll-loop {
width: 300px;
height: 200px;
overflow: hidden;
position: relative;
border: 1px solid #000;
}

#scroll-loop .scroll-content {
position: absolute;
display: flex;
flex-direction: column;
}

#scroll-loop .scroll-content p {
margin: 0;
}
</style>
</head>
<body>

<div id="scroll-loop">
<div class="scroll-content">
<p>头条新闻-1</p>
<p>头条新闻2</p>
<p>头条新闻3</p>
<p>头条新闻4</p>
<p>头条新闻5</p>
<p>头条新闻1</p>
<p>头条新闻2</p>
<p>头条新闻3</p>
<p>头条新闻4</p>
<p>头条新闻5</p>
<p>头条新闻END</p>
<!-- 复制更多新闻以实现无缝滚动效果 -->
</div>
</div>

<script>
function loopScroll(elementId, direction, childCount) {
const scrollContainer = document.getElementById(elementId);
const scrollContent = scrollContainer.firstElementChild;

let scrollAmount = 0;
let scrollSize = 0;
let scrollStep = 1;
let intervalId = null;

if (direction === 'horizontal') {
scrollContainer.style.whiteSpace = 'nowrap';
scrollContent.style.flexDirection = 'row';
scrollSize = scrollContent.offsetWidth;
} else {
scrollSize = scrollContent.offsetHeight;
}

if(!childCount){
// 克隆内容以实现无缝滚动
scrollContent.innerHTML += scrollContent.innerHTML;
}else{
const children = scrollContent.children;
for (let i = 0; i < childCount; i++) {
const child = children[i].cloneNode(true);
scrollContent.appendChild(child);
}
}


function scrollUp() {
if (direction === 'horizontal') {
scrollAmount += scrollStep; // 横向滚动
if (scrollAmount >= scrollSize) {
scrollAmount = 0;
}
scrollContainer.scrollLeft = scrollAmount;
} else {
scrollAmount += scrollStep; // 竖向滚动
if (scrollAmount >= scrollSize) {
scrollAmount = 0;
}
scrollContainer.scrollTop = scrollAmount;
}
}

function startScroll() {
if (!intervalId) {
intervalId = setInterval(scrollUp, 30);
}
}

function stopScroll() {
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
}

// 鼠标进入容器时停止滚动
scrollContainer.addEventListener('mouseenter', stopScroll);
// 鼠标离开容器时继续滚动
scrollContainer.addEventListener('mouseleave', startScroll);

// 初始化时开始滚动
startScroll();
}

// 初始化滚动,传入容器ID, 滚动方向(选填), 克隆节点数量(选填)
loopScroll('scroll-loop', 'vertical', 10); // 'horizontal' 或 'vertical'
</script>

</body>
</html>



声明:星耀夕空|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - js横向或竖向无缝循环滚动


欢迎光顾我的小站!