DIV CSS 佈局教程網

JavaScript 學習筆記之事件對象
編輯:JavaScript基礎知識     

事件是 JavaScript 實現頁面交互的核心。本篇筆記將梳理事件對象的基本概念、跨瀏覽器差異,以及事件綁定的兩種常用方式。

事件對象概述

當事件發生時,瀏覽器會自動建立事件對象,其中包含該事件的類型、鼠標坐標等資訊。事件對象的屬性格式為 event.屬性。

幾點說明:

event 代表事件的狀態,例如觸發事件對象的元素、鼠標的位置及狀態、按下的鍵等等;event 對象只在事件發生的過程中才有效。

需要注意跨瀏覽器的差異:Firefox 裡的 event 與 IE 裡的不同,IE 裡的 event 是全局變量、隨時可用,而 Firefox 裡的 event 需要用參數引導才能使用,是運行時的臨時變量。具體而言,事件的對象在 IE 中是 window.event.srcElement,在 Firefox 中是 event.target,而 Opera 中兩者都可用。

綁定事件的兩種方式

在 JS 中為某個對象(控件)綁定事件,通常有兩種手段。首先在 head 中定義一個函數:

<script type="text/javascript">
  function clickHandler(){
    // do something
    alert("button is clicked!");
  }
</script>

第一種方式:直接在標簽的 onclick 屬性中調用。

<input type="button" value="button1" onclick="clickHandler();">

第二種方式:通過 JS 獲取元素後賦值事件處理函數。

<input type="button" id="button2" value="button2">
<script type="text/javascript">
  var v = document.getElementById("button2");
  v.onclick = clickHandler;  // 這裡用函數名,不能加括號
</script>

其他實例

實例一:通過 onmouseover / onmouseout 改變元素顏色,並在點擊時跳轉。

<!DOCTYPE html>
<html>
<head>
<title>eventTest.html</title>
<script>
  function mOver(object) {
    object.color = "red";
  }
  function mOut(object) {
    object.color = "blue";
  }
</script>
</head>
<body>
  <font style="cursor:help"
    onclick="window.location.href='https://www.baidu.com'"
    onmouseover="mOver(this)" onmouseout="mOut(this)">歡迎訪問</font>
</body>
</html>

實例二:通過 JS 為 document 綁定 mousedown 事件,並讀取事件類型。

<!DOCTYPE html>
<html>
<head>
<title>eventTest2.html</title>
</head>
<body>
  <script type="text/javascript">
    function getEvent(event) {
      alert("事件類型: " + event.type);
    }
    document.write("單擊...");
    document.onmousedown = getEvent;
  </script>
</body>
</html>

掌握事件對象與事件綁定,是實現動態、可交互網頁的關鍵一步。

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