DIV CSS 佈局教程網

滑鼠跟隨特效:把游標換成一隻會被點擊的小手
編輯:JavaScript綜合知識     

把系統游標藏起來,改成一張圖片跟著滑鼠跑,按下時再換成另一張圖,這是很受歡迎的小特效。實作原理只有三件事:隱藏原生游標、用 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>

幾個細節值得注意

  • 加scrollTop 的原因:clientX/clientY 是相對於視窗的座標,而 absolute 定位是相對於文件。頁面向下捲動後兩者會有落差,加上 scrollTop/scrollLeft 才能對齊。
  • 邊界判斷:不减掉 oCursor 的寬高,圖片跑到視窗邊緣時就會被切掉一半。
  • ev || event:為了相容舊 IE 而寫的 event 取得方式,現在直接用參數 ev 就好。

寫法上可以更好的地方

onmousedown 與 onmouseup 寫在 onmousemove 裡面,代表每次滑鼠移動都會重新綁定一次這兩個事件,完全沒有必要——把它們搬到 window.onload 裡跟 onmousemove 平級即可。另外,每次移動都重新指定 innerHTML 會讓瀏覽器重建節點,改用兩張圖片疊放、切換 display 或 background-image 會順很多。

要不要用在正式專案?

自訂游標的可用性爭議不小:它會讓使用者失去系統游標的既/>\not{}</p>

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved