光标样式通过 CSS 的 cursor
属性控制,JavaScript 可通过直接修改 style.cursor
或操作 CSS 类实现动态变更,核心逻辑是监听用户行为(如鼠标移动、点击)并绑定对应的光标样式。
光标类型 | 描述 | 适用场景 |
---|---|---|
default |
默认箭头 | 无特殊交互时 |
pointer |
小手(点击提示) | 可点击的按钮、链接 |
text |
文本输入光标 | <input> 聚焦时 |
move |
移动图标 | 拖拽元素时 |
crosshair |
十字准星 | 精确定位操作 |
wait |
沙漏(加载中) | 异步请求或计算时 |
not-allowed |
禁止符号 | 禁用的表单字段 |
style.cursor
// 全局设置等待光标 document.body.style.cursor = 'wait'; // 恢复默认 document.body.style.cursor = 'default';
/ 定义自定义光标类 / .cursor-magic { cursor: url('magic-cursor.png'), auto; / 使用图片作为光标 / }
// 添加类 element.classList.add('cursor-magic'); // 移除类 element.classList.remove('cursor-magic');
事件类型 | 触发条件 | 示例代码 |
---|---|---|
mouseover |
鼠标悬停元素 | element.addEventListener('mouseover', () => element.style.cursor = 'pointer'); |
mousedown |
鼠标按下 | element.addEventListener('mousedown', () => document.body.style.cursor = 'grabbing'); |
mouseleave |
鼠标移出元素 | element.addEventListener('mouseleave', () => element.style.cursor = 'default'); |
dragstart |
开始拖拽 | element.addEventListener('dragstart', () => element.style.cursor = 'move'); |
url()
格式。grabbing
),需提供备用方案。touch-action
CSS 属性优化体验。解答:
若全局修改了 document.body.style.cursor
,只需将其重置为 'default'
,若通过类控制,需移除对应类:
// 全局恢复 document.body.style.cursor = ''; // 或设为 'default' // 移除自定义类 element.classList.remove('cursor-magic');
解答:
光标样式变更本身性能开销极低,但需注意:
document.querySelectorAll
统一操作