scrolltext js实现
使用 JavaScript 实现滚动文本
方法一:使用 marquee 标签(已废弃,但简单)
虽然 marquee 标签已废弃,但在某些场景下仍可使用:
<marquee behavior="scroll" direction="left">这是滚动文本内容</marquee>
方法二:使用 CSS 动画
通过 CSS 的 @keyframes 实现平滑滚动:
<div class="scroll-container">
<div class="scroll-text">这是需要滚动的文本内容</div>
</div>
<style>
.scroll-container {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.scroll-text {
display: inline-block;
animation: scroll 10s linear infinite;
}
@keyframes scroll {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
</style>
方法三:纯 JavaScript 实现
动态计算位置实现可控滚动:
<div id="scroller" style="width:300px; overflow:hidden; border:1px solid #ccc;">
<span id="scrollText">这是需要滚动的长文本内容...</span>
</div>
<script>
const scroller = document.getElementById('scroller');
const text = document.getElementById('scrollText');
let position = scroller.offsetWidth;
function scroll() {
position--;
if (position < -text.offsetWidth) {
position = scroller.offsetWidth;
}
text.style.transform = `translateX(${position}px)`;
requestAnimationFrame(scroll);
}
scroll();
</script>
方法四:使用第三方库(如 jQuery)
若项目已使用 jQuery,可简化实现:
<div class="scroll-box">这是需要滚动的文本内容...</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
const $box = $('.scroll-box');
const width = $box.width();
const contentWidth = $box[0].scrollWidth;
function animate() {
$box.css('margin-left', -contentWidth + 'px');
$box.animate(
{ 'margin-left': width + 'px' },
10000,
'linear',
animate
);
}
animate();
});
</script>
注意事项
- 性能优化:对于长文本或高频更新内容,建议使用 CSS 动画而非 JavaScript 计算
- 响应式设计:滚动容器宽度应适配不同屏幕尺寸
- 可访问性:确保滚动内容可被屏幕阅读器识别,必要时添加 ARIA 标签
以上方法可根据具体需求选择,CSS 动画方案在多数现代浏览器中性能最佳。







