把系統游標藏起來,改成一張圖片跟著滑鼠跑,按下時再換成另一張圖,這是很受歡迎的小特效。實作原理只有三件事:隱藏原生游標、用 position: absolute 的 div 跟著 clientX/clientY 移動、在 mousedown 與 mouseup 時替換圖片。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>可愛的滑鼠跟隨</title>
<style>
html { background: #000; }
body, html, input { cursor: none; } /* 隱藏原生游標 */
body, html { height: 100%; }
#cursor {
position: absolute;
left: 100px;
top: 100px;
display: block;
}
</style>
<script>
window.onload = function () {
var oCursor = document.getElementById("cursor");
document.onmousemove = function (ev) {
var oEvent = ev || event;
var oWidth = document.documentElement.clientWidth;
var oHeight = document.documentElement.clientHeight;
var scrollTop = document.documentElement.scrollTop + oEvent.clientY;
var scrollLeft = document.documentElement.scrollLeft + oEvent.clientX;
// 上下邊界:不要超出視窗
if (scrollTop > oHeight - oCursor.offsetHeight) {
oCursor.style.top = oHeight - oCursor.offsetHeight + 'px';
} else if (scrollTop < 0) {
oCursor.style.top = 0;
} else {
oCursor.style.top = scrollTop + 'px';
}
// 左右邊界
if (scrollLeft > oWidth - oCursor.offsetWidth) {
oCursor.style.left = oWidth - oCursor.offsetWidth + 'px';
} else {
oCursor.style.left = scrollLeft + 'px';
}
// 按下時換成「被點擊」的圖
document.onmousedown = function () {
oCursor.innerHTML = "<img src='cursor_hover.png' />";
return false;
};
// 放開時換回來
document.onmouseup = function () {
oCursor.innerHTML = "<img src='cursor.png' />";
};
};
};
</script>
</head>
<body>
<div id="cursor"><img src="cursor.png" /></div>
<input type="button" style="font-size:36px; margin:100px;"
value="點擊" onclick="window.open('https://www.example.com')" />
</body>
</html>
onmousedown 與 onmouseup 寫在 onmousemove 裡面,代表每次滑鼠移動都會重新綁定一次這兩個事件,完全沒有必要——把它們搬到 window.onload 裡跟 onmousemove 平級即可。另外,每次移動都重新指定 innerHTML 會讓瀏覽器重建節點,改用兩張圖片疊放、切換 display 或 background-image 會順很多。
自訂游標的可用性爭議不小:它會讓使用者失去系統游標的既/>\not{}</p>