多行文字向左无缝滚动是一种常见的网页动画效果,通常用于展示新闻、公告等信息。这种效果通过JavaScript控制DOM元素的样式属性,使其在页面上以一定的速度向左移动,当文字移出可视区域后,再从右侧重新进入,从而实现无缝滚动的效果。
以下是一个简单的JavaScript实现多行文字向左无缝滚动的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>多行文字向左无缝滚动</title>
<style>
#scrollContainer {
width: 100%;
overflow: hidden;
white-space: nowrap;
position: relative;
}
#scrollContent {
display: inline-block;
animation: scrollLeft 15s linear infinite;
}
@keyframes scrollLeft {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
</style>
</head>
<body>
<div id="scrollContainer">
<div id="scrollContent">
这是一段需要滚动显示的文字。这是一段需要滚动显示的文字。这是一段需要滚动显示的文字。
</div>
</div>
<script>
function startScroll() {
const container = document.getElementById('scrollContainer');
const content = document.getElementById('scrollContent');
const clone = content.cloneNode(true);
container.appendChild(clone);
content.addEventListener('animationiteration', () => {
content.style.animationPlayState = 'paused';
setTimeout(() => {
content.style.animationPlayState = 'running';
}, 10);
});
}
window.onload = startScroll;
</script>
</body>
</html>
requestAnimationFrame
来控制动画帧率。linear
)来控制动画速度,并确保页面其他脚本不会干扰动画的执行。通过以上方法,可以实现一个稳定且流畅的多行文字向左无缝滚动效果。
领取专属 10元无门槛券
手把手带您无忧上云