You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript向下滚动文本左右移动动画:mousemove代码如何适配scroll触发

修复后的实现方案

核心调整逻辑

  • 事件监听从鼠标移动事件切换为页面滚动事件
  • 位移计算基准从鼠标横坐标替换为页面垂直滚动距离,匹配「向下滚动文本右移」的需求
  • 保留原有的data-value自定义速度配置能力

可直接运行的代码

<script type="text/javascript">
    // 绑定滚动事件
    window.addEventListener("scroll", animation);
    // 页面初始化时执行一次,避免初始状态错位
    animation();

    function animation() {
        // 获取页面垂直滚动距离
        const scrollY = window.scrollY;
        document.querySelectorAll(".object").forEach(function (move) {
            const moving_value = move.getAttribute("data-value");
            // 这里的75可以自行调整,数值越大整体移动速度越慢
            const x = (scrollY * moving_value) / 75;
            move.style.transform = "translateX(" + x + "px)";
        });
    }
</script>

可选优化项

如果滚动时出现掉帧,可以加节流逻辑限制触发频率,修改后的代码如下:

<script type="text/javascript">
    let isThrottled = false;
    window.addEventListener("scroll", () => {
        if (isThrottled) return;
        isThrottled = true;
        requestAnimationFrame(animation);
        setTimeout(() => isThrottled = false, 16); // 约60帧的触发频率
    });
    animation();

    function animation() {
        const scrollY = window.scrollY;
        document.querySelectorAll(".object").forEach(function (move) {
            const moving_value = move.getAttribute("data-value");
            const x = (scrollY * moving_value) / 75;
            move.style.transform = "translateX(" + x + "px)";
        });
    }
</script>

如果需要实现元素进入可视区域后才开始移动的效果,可额外增加IntersectionObserver判断元素可见性即可。

内容的提问来源于stack exchange,提问作者Erdenay Karataş

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 17:18:04