js实现游标
使用JavaScript实现游标
在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法:
修改默认鼠标指针样式
通过CSS的cursor属性可以修改元素的鼠标指针样式:
.element {
cursor: pointer; /* 手型指针 */
cursor: url('custom-cursor.png'), auto; /* 自定义图片 */
}
JavaScript动态修改:
document.getElementById('myElement').style.cursor = 'wait'; /* 等待状态 */
创建自定义游标元素
完全替换默认指针,创建一个跟随鼠标移动的DOM元素:
const customCursor = document.createElement('div');
customCursor.style.position = 'fixed';
customCursor.style.width = '20px';
customCursor.style.height = '20px';
customCursor.style.backgroundColor = 'red';
customCursor.style.borderRadius = '50%';
customCursor.style.pointerEvents = 'none'; /* 防止遮挡点击事件 */
document.body.appendChild(customCursor);
document.addEventListener('mousemove', (e) => {
customCursor.style.left = `${e.clientX}px`;
customCursor.style.top = `${e.clientY}px`;
});
/* 隐藏默认指针 */
document.body.style.cursor = 'none';
高级游标交互效果
实现带延迟跟随效果的游标:
const cursor = document.getElementById('cursor');
let mouseX = 0, mouseY = 0;
let posX = 0, posY = 0;
function animate() {
posX += (mouseX - posX) / 5; /* 延迟系数 */
posY += (mouseY - posY) / 5;
cursor.style.transform = `translate3d(${posX}px, ${posY}px, 0)`;
requestAnimationFrame(animate);
}
document.addEventListener('mousemove', (e) => {
mouseX = e.clientX;
mouseY = e.clientY;
});
animate();
响应式游标状态
根据交互元素改变游标样式:
const hoverElements = document.querySelectorAll('.hover-effect');
hoverElements.forEach(el => {
el.addEventListener('mouseenter', () => {
cursor.classList.add('cursor-hover');
});
el.addEventListener('mouseleave', () => {
cursor.classList.remove('cursor-hover');
});
});
对应CSS:
.cursor-hover {
transform: scale(1.5);
background-color: blue;
}
性能优化建议
- 使用
transform代替top/left定位以获得更好的性能 - 限制
mousemove事件的触发频率 - 对自定义游标使用硬件加速:
.custom-cursor { will-change: transform; }
浏览器兼容性注意事项
- 自定义游标图片格式需注意浏览器支持情况
- 移动端设备可能需要特殊处理
- 某些浏览器可能限制自定义游标的最小尺寸
以上方法可以根据具体需求组合使用,实现从简单样式修改到复杂交互游标的各种效果。







