如何使用AlpineJS追踪div内鼠标的像素位置?
使用AlpineJS追踪div内鼠标坐标(适配TailwindCSS径向模糊需求)
要实现div内鼠标坐标的实时追踪,同时输出数字+px格式的字符串,你可以通过以下方式修改代码:
核心实现步骤
- 给目标div绑定
mousemove事件,通过AlpineJS的@mousemove指令监听鼠标移动 - 在事件回调中计算鼠标相对于div内部的坐标(而非全局视口坐标)
- 将计算后的坐标拼接上
px,更新到mouseX和mouseY变量中
完整代码示例
<div x-data="{ mouseX: '0px', mouseY: '0px' }" @mousemove=" const rect = $event.currentTarget.getBoundingClientRect(); mouseX = `${Math.round($event.clientX - rect.left)}px`; mouseY = `${Math.round($event.clientY - rect.top)}px`; " class="relative w-full h-96 bg-gray-100" > <!-- 示例:用Tailwind任意值绑定坐标实现径向模糊效果 --> <div class="absolute inset-0 bg-white/20 backdrop-blur-md [mask-image:radial-gradient(150px_at_var(--mouse-x)_var(--mouse-y),white,transparent)]" :style="{ '--mouse-x': mouseX, '--mouse-y': mouseY }" ></div> </div>
关键细节说明
- 相对坐标计算:通过
getBoundingClientRect()获取div的视口位置,用鼠标的全局坐标减去div的偏移量,得到div内部的相对坐标,避免页面布局偏移导致坐标错误 - 格式处理:用模板字符串直接拼接数字与
px,精准满足你需要的格式要求 - Tailwind适配:通过
:style动态绑定CSS变量,再在Tailwind的任意值语法中引用变量,实现基于鼠标位置的径向模糊遮罩效果
内容的提问来源于stack exchange,提问作者Keida
相关产品推荐
相关产品推荐

