## DOM 事件 DOM 「事件」是在網頁或瀏覽器環境中,發生的特定動作或行為。 例如點擊按鈕、滾動滾輪、按下鍵盤鍵等。 它讓 JavaScript 在這些事件動作發生時,可以執行特定的代碼,並促成互動式網頁的基本機制。 ## 常見的DOM事件 DOM 定義了許多種事件,以下列出一些常見的事件: * click:當使用者點擊元素時觸發。 * mousemove:當滑鼠在元素上移動時觸發。 * keydown:當使用者按下鍵盤按鍵時觸發。 * load:當瀏覽器完成載入網頁時觸發。 * change:當表單元素的值被改變時觸發。 ## 事件監聽器 ``` document.addEventListener(event, function); ``` ## 範例1 Hello ```xml <!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> <h1>Hello!</h1> <form> <input autofocus id="name" placeholder="Name" type="text"> <input type="submit"> </form> </body> <script> document.querySelector('form').addEventListener('submit', function(){ let name = document.querySelector('#name').value; alert(`Hello, ${name}!`); }); </script> </html> ``` ## Project1 ::: success 請寫一個heading 上面寫 HELLO 跟一個按鈕 按下按鈕可以 讓heading 在 HELLO 跟 GOODBYE 做切換 ::: ## 範例2 Counter ```xml <!DOCTYPE html> <html> <head> <title>Counter</title> </head> <body> <h1>0</h1> <button>Count</button> </body> <script> let counter = 0; document.querySelector('button').addEventListener('click', function count(){ counter ++; document.querySelector('h1').innerHTML = counter; } }); </script> </html> ``` ## Project 2 :::success 針對範例題目做修改 增加新功能: 1. counter 數到10的倍數時 會跳出一個 alert 報數 2. 新增一個reset 按鈕 可以讓 counter 歸零 ::: 其實DOM操作還可以做到很多事情,可以修改節點屬性 CSS 內容。甚至還可以增加跟刪除節點 ## 範例3 Color ```xml= <!DOCTYPE html> <html> <head> <title>Colors</title> </head> <body> <h1 id="hello">Hello!</h1> <button date-color="red">Red</button> <button data-color="blue">Blue</button> <button data-color="green">Green</button> </body> <script> //change font color to red document.querySelector("#red").onclick = function(){ document.querySelector('#hello').style.color = 'red'; }; //change font color to blue document.querySelector("#blue").onclick = function(){ document.querySelector('#hello').style.color = 'blue'; }; //change font color to green document.querySelector("#green").onclick = function(){ document.querySelector('#hello').style.color = 'green'; }; </script> </html> ``` ## Project 3 :::success 很簡單 將按鈕修改成更改字體大小 (大中小) :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up