隱藏系統默認鼠標,使用自定義圖片作為游標,滑動跟隨,點擊時切換為「點擊態」圖片,鬆開恢復。純原生 JS 實現,無依賴。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>自定義鼠標跟隨特效</title>
<style>
html, body {
height: 100%;
margin: 0;
background: #000; /* 深色背景便於觀察白色游標 */
}
/* 隱藏原生游標 */
body, html, input, button, a {
cursor: none !important;
}
/* 自定義游標容器 */
#customCursor {
position: fixed; /* 相對視口定位,不受滾動影響 */
left: 0;
top: 0;
pointer-events: none; /* 關鍵:讓鼠標事件穿透到底層元素 */
z-index: 9999;
transition: transform 0.05s linear; /* 可選:添加微小延遲增加跟隨感 */
transform: translate(-50%, -50%); /* 圖片中心對齊鼠標熱點 */
}
#customCursor img {
width: 32px;
height: 32px;
display: block;
}
</style>
</head>
<body>
<div id="customCursor">
<img id="cursorImg" src="https://example.com/cursor-default.png" alt="cursor">
</div>
<!-- 測試用按鈕 -->
<button style="font-size: 24px; margin: 100px auto; display: block;" onclick="window.open('https://example.com')">點擊跳轉</button>
<script>
(function() {
var cursor = document.getElementById('customCursor');
var img = document.getElementById('cursorImg');
var defaultSrc = 'https://example.com/cursor-default.png';
var activeSrc = 'https://example.com/cursor-click.png';
// 初始居中
cursor.style.left = '50%';
cursor.style.top = '50%';
// 滑動跟隨
document.addEventListener('mousemove', function(e) {
// 使用 clientX/Y + 滾動偏移 = 頁面座標,但 fixed 定位只需 clientX/Y
cursor.style.left = e.clientX + 'px';
cursor.style.top = e.clientY + 'px';
});
// 按下/鬆開切換圖片
document.addEventListener('mousedown', function() {
img.src = activeSrc;
});
document.addEventListener('mouseup', function() {
img.src = defaultSrc;
});
// 頁面卸載時恢復默認游標(可選)
window.addEventListener('beforeunload', function() {
document.body.style.cursor = 'auto';
});
})();
</script>
</body>
</html>
自定義游標能增強品牌識別度和交互趣味性,但需謹慎使用:確保不影響可訪問性、提供關閉開關、移動端自動禁用。核心只需 20 行 JS + 幾行 CSS,輕鬆打造獨特體驗。