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

JavaScript鼠标响应视差效果失效问题排查与解决

视差效果JavaScript无响应的修复方案

一、JavaScript核心错误修复

1. 未定义变量与作用域错误

zValue未在全局作用域声明,且mousemove事件中错误引用了forEach循环内的el变量,导致代码执行中断。同时部分元素缺失data-speedz/data-rotation属性,会引发undefined计算错误。

2. 函数逻辑与参数不匹配

update函数接收的cursorPosition参数未实际使用,初始调用update(0)无意义,需调整逻辑并补全默认值处理。

修复后的完整JavaScript代码:

const parallax_el = document.querySelectorAll(".parallax");

let xValue = 0, 
  yValue = 0;
let rotateDegree = 0; 

function update() {
  parallax_el.forEach ((el) => {
    // 给缺失的data属性设置默认值,避免计算报错
    let speedx = parseFloat(el.dataset.speedx) || 0;
    let speedy = parseFloat(el.dataset.speedy) || 0;
    let speedz = parseFloat(el.dataset.speedz) || 0;
    let rotateSpeed = parseFloat(el.dataset.rotation) || 0;

    // 针对每个元素计算z轴偏移
    const elLeft = parseFloat(getComputedStyle(el).left);
    const isInLeft = elLeft < window.innerWidth / 2 ? 1 : -1;
    const zValue = (xValue - elLeft) * isInLeft * 0.1;

    // 调整transform顺序,保证透视效果生效
    el.style.transform = `perspective(2300px) translateX(calc(-50% + ${-xValue * speedx}px)) translateY(calc(-50% + ${yValue * speedy}px)) rotateY(${rotateDegree * rotateSpeed}deg) translateZ(${zValue * speedz}px)`;
  });
}

// 初始化调用
update();
    
window.addEventListener("mousemove", (e) => {
  xValue = e.clientX - window.innerWidth / 2;
  yValue = e.clientY - window.innerHeight / 2;

  rotateDegree = (xValue / (window.innerWidth / 2)) * 20;

  update();
});

二、CSS语法错误修复

.parallax类的transition属性存在多余括号,会导致过渡效果失效:

.parallax {
    pointer-events: none;
    /* 修复前:transition: 0.45s (cubic-bezier(.2,.49,.32,.99)); */
    transition: 0.45s cubic-bezier(.2,.49,.32,.99);
    transform: translate(-50%, -50%);
}

三、额外优化建议

  • 给所有.parallax元素补全data-speedz和data-rotation属性,减少JS中默认值处理的性能消耗。
  • 添加防抖函数优化mousemove事件触发频率,避免频繁重绘:
function debounce(func, delay = 10) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, args), delay);
  };
}

window.addEventListener("mousemove", debounce((e) => {
  xValue = e.clientX - window.innerWidth / 2;
  yValue = e.clientY - window.innerHeight / 2;

  rotateDegree = (xValue / (window.innerWidth / 2)) * 20;

  update();
}));

内容的提问来源于stack exchange,提问作者Karael Zexceed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:07:27