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

如何实现固定初始位置的红色div跟随自定义光标呈现连线效果

实现方案

核心思路是先获取红色div固定原点的坐标,再计算原点到光标位置的距离(作为红色div的高度)、两点连线的旋转角度,直接赋值给红色div即可。

完整可运行代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>连线跟随光标效果</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      overflow: hidden;
      width: 100%;
      height: 100vh;
      background: black;
      position: relative;
    }

    .cursor {
      position: fixed;
      width: 5rem;
      height: 5rem;
      border-radius: 10px;
      background: black;
      box-shadow: 0px 0px 20px white;
      z-index: 11;
      /* 修正光标定位基准点为中心 */
      transform: translate(-50%, -50%);
      pointer-events: none;
    }

    .follow_cursor {
      position: absolute;
      background: red;
      width: 5rem;
      z-index: 2;
      /* 固定起始点位置 */
      top: 10%;
      left: 80%;
      transform-origin: top center;
      pointer-events: none;
    }

    .follow_cursor::after {
      position: absolute;
      content: "";
      top: 100%;
      left: 0;
      background: white;
      z-index: 3;
      width: 5rem;
      height: 5rem;
      transform: translateY(-50%);
    }
  </style>
</head>
<body>
  <div class="follow_cursor"></div>
  <div class="cursor"></div>
  
  <script>
    const cursor = document.querySelector(".cursor");
    const follow = document.querySelector(".follow_cursor");
    // 先获取红色div的固定原点坐标(顶部中心)
    const followRect = follow.getBoundingClientRect();
    const startX = followRect.left + followRect.width / 2;
    const startY = followRect.top;

    document.onmousemove = (e) => {
      const x = e.pageX;
      const y = e.pageY;
      
      // 自定义光标定位
      cursor.style.left = `${x}px`;
      cursor.style.top = `${y}px`;

      // 计算两点的x、y差值
      const dx = x - startX;
      const dy = y - startY;
      // 计算两点距离,作为红色div的高度
      const distance = Math.sqrt(dx * dx + dy * dy);
      follow.style.height = `${distance}px`;
      // 计算旋转角度,弧度转角度
      const angle = Math.atan2(dy, dx) * 180 / Math.PI - 90;
      follow.style.transform = `rotateZ(${angle}deg)`;
    };
  </script>
</body>
</html>

关键修改说明

  • 修正了自定义光标的定位偏移:给.cursor加了transform: translate(-50%, -50%),让光标中心和鼠标位置对齐
  • 提前计算红色div的固定起始点坐标,避免每次鼠标移动都重复计算
  • 用Math.sqrt计算两点直线距离作为红色div的高度,替代原来直接用鼠标y坐标赋值的错误逻辑
  • 用Math.atan2计算两点连线的实际旋转角度,替代原来按x坐标比例估算角度的错误逻辑
  • 给交互元素加了pointer-events: none,避免遮挡页面其他元素的交互

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:57:03