DIV CSS 佈局教程網

JavaScript 程式入門(第五課):滑鼠事件(上)
編輯:JavaScript基礎知識     

隨著課程推進,能一路跟下來的人越來越少。其實網頁上大量的動態特效,大多是以 JavaScript 實作的——沒有 JavaScript 的網頁,就像一個人失去了肌肉。而所有的動作都由函式來控制,控制語句正是這一切的基礎。這一課我們來點能立刻看到效果的內容:滑鼠事件。

常見的滑鼠事件

1. mouseover(滑鼠移入)
2. mouseout(滑鼠移出)
3. mousemove(滑鼠移動)
4. mousedown(滑鼠按下)
5. mouseup(滑鼠放開)
6. click(單擊)
7. dblclick(雙擊)

其中 1 和 2 通常成對使用:當使用者把滑鼠移到某個連結或元素上時觸發 mouseover,移開時則觸發 mouseout。

範例一:滑鼠移入移出改變字型樣式

<script language="javascript">
function text_onmouseover(){
  mytext.style.fontSize = "30pt";
  mytext.style.color = "red";
  mytext.style.fontStyle = "italic";
}
function text_onmouseout(){
  mytext.style.fontSize = "20pt";
  mytext.style.color = "blue";
  mytext.style.fontStyle = "normal";
}
</script>
<p id="mytext" onmouseover="text_onmouseover()"
   onmouseout="text_onmouseout()">https://www.example.com</p>

這裡定義了兩個函式來切換字型樣式。要注意:IE 對頁面上所有元素都支援 mouseover 與 mouseout,但早期的 Netscape Navigator 只對超連結與層(layer)支援這兩個事件。

範例二:滑鼠移動時顯示座標

<SCRIPT LANGUAGE="JavaScript">
if (navigator.appName == 'Netscape')
{
  document.captureEvents(Event.MOUSEMOVE);
  document.onmousemove = netscapeMouseMove;
}
function netscapeMouseMove(e) {
  if (e.screenX != document.test.x.value
      && e.screenY != document.test.y.value) {
    document.test.x.value = e.screenX;
    document.test.y.value = e.screenY;
  }
}
function micro$oftMouseMove() {
  if (window.event.x != document.test.x.value
      && window.event.y != document.test.y.value) {
    document.test.x.value = window.event.x;
    document.test.y.value = window.event.y;
  }
}
</SCRIPT>

滑鼠移動事件常用在「滑鼠跟隨」這類特效上。需要注意的是,啟動這個事件處理可能會干擾其他事件,也會增加頁面處理時間,因此應盡量少用。

本課作業

1. 圖片連結切換:滑鼠移上去時顯示一張圖,移開時換成另一張圖。
2. 圖片跟隨滑鼠:滑鼠移動時,有一張圖片跟著一起移動。

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