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

Javascript控制CSS绘制的圆形跟随鼠标移动功能失效求助

代码问题修复说明
  • 核心问题:JavaScript 模板字符串语法使用错误
    你在为元素设置style.cssText时使用了普通单引号包裹字符串,导致${x}、${y}的变量插值逻辑不会生效,浏览器会把插值语法当做普通文本处理,无法正确给元素赋值坐标。只需要把包裹字符串的单引号替换为反引号(`,键盘ESC键下方按键)即可解决。
  • 可选优化:避免跟随元素阻塞页面交互
    两个鼠标跟随元素默认会捕获鼠标事件,会遮挡下方页面元素的点击、悬浮等交互响应,在两个元素的CSS规则中添加pointer-events: none属性即可解决该问题。

修复后的完整JS代码

const mouseCircle = document.querySelector(".mouse-circle");
const mouseDot = document.querySelector(".mouse-dot");

//Mouse Circle
const mouseCircleFn = (x,y) => {
    // 单引号替换为反引号生效模板插值
    mouseCircle.style.cssText = `top: ${y}px; left: ${x}px`;
    mouseDot.style.cssText = `top: ${y}px; left: ${x}px`;
};

document.body.addEventListener("mousemove", (e) => {
    let x = e.clientX;
    let y = e.clientY;
    mouseCircleFn(x,y);
});
//End of Mouse Circle

优化后的CSS对应片段

.mouse-circle,
.mouse-dot{
    border-radius: 50%;
    position: fixed;
    z-index: 300;
    transform: translate(-50%, -50%);
    /* 新增属性,避免元素拦截鼠标事件 */
    pointer-events: none;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:45:04