效果见蓝色方块。(移动端不支持)

这里就要用到之前提到过wheelEvent

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// ...

useEffect(() => {
  const handleWheel = (e) => {
    // 拿初始位置
    const left = nodePosRef.current.x;
    const top = nodePosRef.current.y;

    // 鼠标滚动的距离
    const diffX = e.deltaX;
    const diffY = e.deltaY;

    // 目标位置
    const targetNodeX = left - diffX;
    const targetNodeY = top - diffY;

    setStyle({ x: targetNodeX, y: targetNodeY });

    // 记录上一次的位置
    nodePosRef.current.x = targetNodeX;
    nodePosRef.current.y = targetNodeY;
  };

  window.addEventListener("wheel", handleWheel);
  return () => {
    window.removeEventListener("wheel", handleWheel);
  };
}, []);