跟随鼠标的十字准星
用 ::before 和 ::after 绘制十字线,mousemove 更新位置:
<style>
#crosshair {
position: fixed;
width: 20px;
height: 20px;
pointer-events: none; /* 不阻挡下层元素的鼠标事件 */
z-index: 99999;
}
#crosshair::before,
#crosshair::after {
content: "";
position: absolute;
background: red;
}
/* 垂直线 */
#crosshair::before {
left: 50%;
top: 0;
width: 1px;
height: 100%;
transform: translateX(-50%);
}
/* 水平线 */
#crosshair::after {
top: 50%;
left: 0;
width: 100%;
height: 1px;
transform: translateY(-50%);
}
</style>
<div id="crosshair"></div>
<script>
const crosshair = document.getElementById("crosshair");
document.addEventListener("mousemove", (e) => {
crosshair.style.left = `${e.clientX - 10}px`;
crosshair.style.top = `${e.clientY - 10}px`;
});
</script>
pointer-events: none 让准星元素”透明”——鼠标事件穿透到下层元素。
全屏辅助线(贯穿整个视口)
<style>
.guide-h, .guide-v {
position: fixed;
pointer-events: none;
z-index: 99999;
opacity: 0.4;
}
.guide-h {
width: 100vw;
height: 1px;
left: 0;
background: #00aaff;
}
.guide-v {
height: 100vh;
width: 1px;
top: 0;
background: #00aaff;
}
</style>
<div class="guide-h" id="guideH"></div>
<div class="guide-v" id="guideV"></div>
<script>
const guideH = document.getElementById("guideH");
const guideV = document.getElementById("guideV");
document.addEventListener("mousemove", (e) => {
guideH.style.top = `${e.clientY}px`;
guideV.style.left = `${e.clientX}px`;
});
</script>
水平线跟随 clientY,垂直线跟随 clientX,始终贯穿整个视口。
显示/隐藏辅助线(快捷键切换)
let visible = true;
document.addEventListener("keydown", (e) => {
if (e.key === "h") { // 按 H 键切换
visible = !visible;
guideH.style.display = visible ? "block" : "none";
guideV.style.display = visible ? "block" : "none";
}
});
CSS cursor 常用值
/* 标注/选择场景 */
cursor: crosshair; /* 十字准星 */
cursor: cell; /* 单元格十字 */
/* 拖拽场景 */
cursor: grab; /* 手型(可拖拽) */
cursor: grabbing; /* 手型(拖拽中)*/
cursor: move; /* 四方向箭头 */
/* 调整大小 */
cursor: col-resize; /* 左右调宽 */
cursor: row-resize; /* 上下调高 */
cursor: nwse-resize; /* 左上-右下对角 */
cursor: nesw-resize; /* 右上-左下对角 */
/* 缩放 */
cursor: zoom-in;
cursor: zoom-out;
/* 禁止操作 */
cursor: not-allowed;
自定义图片作为鼠标
.custom-cursor {
cursor: url("/img/cursor.png") 8 8, crosshair;
/* url(...) 8 8 表示热点坐标(点击点相对图片左上角的偏移) */
/* 第二个值是 fallback cursor,浏览器不支持时使用 */
}
图片尺寸建议不超过 128x128px,PNG 格式,透明背景。
Canvas 中覆盖系统鼠标
// 隐藏系统鼠标指针
canvas.style.cursor = "none";
// 在 Canvas 内自行绘制准星
canvas.addEventListener("mousemove", (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
ctx.clearRect(0, 0, canvas.width, canvas.height);
// ... 重绘内容 ...
// 绘制准星
ctx.strokeStyle = "red";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(x - 10, y);
ctx.lineTo(x + 10, y);
ctx.moveTo(x, y - 10);
ctx.lineTo(x, y + 10);
ctx.stroke();
});
Canvas 场景下用 cursor: none + 手动绘制是最常见的方式,可以精确控制准星样式和动画。
