Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 文字滚动

作者:▄对对碰   发布日期:2026-04-22   浏览:99

<!DOCTYPE html>
<html>
<head>
    <title>JS 文字滚动</title>
    <style>
        #scrollText {
            width: 300px;
            height: 50px;
            overflow: hidden;
            position: relative;
            border: 1px solid #ccc;
            background-color: #f9f9f9;
            padding: 5px;
        }
        #scrollText div {
            position: absolute;
            width: 100%;
            height: 100%;
            display: inline-block;
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <div id="scrollText">
        <div id="text">这是一个文字滚动的示例,用于展示如何使用 JavaScript 实现文字滚动效果。</div>
    </div>

    <script>
        (function() {
            var text = document.getElementById('text');
            var scrollText = document.getElementById('scrollText');
            var textWidth = text.offsetWidth;
            var scrollWidth = scrollText.offsetWidth;
            var distance = 0;

            function scroll() {
                if (distance < -textWidth) {
                    distance = scrollWidth;
                } else {
                    distance -= 2;
                }
                text.style.left = distance + 'px';
                requestAnimationFrame(scroll);
            }

            // 初始化文本位置
            text.style.position = 'absolute';
            text.style.left = scrollWidth + 'px';

            // 开始滚动
            scroll();
        })();
    </script>
</body>
</html>

解释说明:

  1. HTML结构:包含一个 div 元素,其内部有一个子 div 用于显示滚动的文字。
  2. CSS样式
    • 设置了 #scrollText 的宽度、高度和溢出隐藏属性,确保超出部分不可见。
    • 使用绝对定位 (position: absolute) 来控制文字的位置。
  3. JavaScript逻辑
    • 获取文字和容器的宽度。
    • 定义 scroll 函数,通过不断减少 left 属性值来实现文字向左滚动的效果。
    • 当文字完全移出视口时,重置其位置到右侧并继续滚动。
    • 使用 requestAnimationFrame 实现平滑的动画效果。

这样就可以实现一个简单的水平文字滚动效果。

上一篇:js 添加css

下一篇:js 添加样式

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站