
瀏覽器中有許多的事件,筆記常用的像是滑鼠點擊、移動事件、鍵盤輸入事件、冒泡事件…等,事件通常與函式搭配使用,在事件發生前函式不會被執行!
舉例:點擊按鈕的事件
1
   | <input type="button" class="btn" value="CLICK" />
   | 
 
使用 querySelctor 綁定 .btn,並給予一個點擊事件 onclick,上方有講到,事件通常會配搭函示使用,所以程式碼會變成:
1 2
   | var el = document.querySelctor(".btn"); el.onclick = function () {};
  | 
 
function 後面的括弧中,可以帶入參數,若是事件,會帶 event 或是 e,在參數的位置,告訴 function 這會是一個事件,這邊帶一個點擊後會執行 alert 。
1 2 3 4
   | var el = document.querySelector(".btn"); el.onclick = function (e) {   alert("click"); };
  | 
 
codepen: https://codepen.io/hnzxewqw/pen/xxGgrbQ
以上顯示效果成功後,用 console.log(e); 來看一下除了 alert 顯示外,還有什麼資訊可以查看,
點擊後在 console.log 裡面會看到一個物件資料:
1
   | MouseEvent {isTrusted: true, screenX: 56, screenY: 572, clientX: 56, clientY: 37, …}
  | 
 
點開後會看到以下詳細的資訊,而這些資訊在不同的專案上,會是很有用的參考資料:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
   | MouseEvent {isTrusted: true, screenX: 56, screenY: 572, clientX: 56, clientY: 37, …} isTrusted: true screenX: 56 screenY: 572 clientX: 56  clientY: 37  ctrlKey: false  shiftKey: false altKey: false metaKey: false button: 0 buttons: 0 relatedTarget: null pageX: 56 pageY: 37 x: 56 y: 37 offsetX: 46 offsetY: 27 movementX: 0 movementY: 0 fromElement: null toElement: input.btn layerX: 56 layerY: 37 view: Window {parent: global, opener: null, top: global, length: 0, frames: Window, …} detail: 1 sourceCapabilities: InputDeviceCapabilities {firesTouchEvents: false} which: 1 type: "click"  target: input.btn currentTarget: null eventPhase: 0 bubbles: true cancelable: true defaultPrevented: false composed: true timeStamp: 25442.33000000008 srcElement: input.btn returnValue: true cancelBubble: false path: (5) [input.btn, body, html, document, Window] __proto__: MouseEvent
  |