在 JavaScript 里,事件是在文檔或者瀏覽器窗口中發生的特定交互瞬間,例如點擊按鈕、頁面加載完成等等。下面是一些常用的事件以及案例:
1.?click
?事件
當用戶點擊元素時觸發
const button = document.createElement('button');
button.textContent = '點擊我';
document.body.appendChild(button);button.addEventListener('click', function() {alert('按鈕被點擊了!');
});
2.?mouseover
?事件
當鼠標指針移動到元素上方時觸發。
const box = document.createElement('div');
box.style.width = '100px';
box.style.height = '100px';
box.style.backgroundColor = 'blue';
document.body.appendChild(box);box.addEventListener('mouseover', function() {this.style.backgroundColor = 'red';
});
3.?mouseout
?事件
當鼠標指針移出元素時觸發。
const box = document.createElement('div');
box.style.width = '100px';
box.style.height = '100px';
box.style.backgroundColor = 'blue';
document.body.appendChild(box);box.addEventListener('mouseout', function() {this.style.backgroundColor = 'green';
});
4.?keydown
?事件
當用戶按下鍵盤上的某個鍵時觸發。
document.addEventListener('keydown', function(event) {console.log(`你按下了 ${event.key} 鍵`);
});
5.?load
?事件
當頁面或圖像等資源加載完成時觸發。
<body><img id="myImage" src="https://picsum.photos/200/300" alt="示例圖片"><script>const image = document.getElementById('myImage');image.addEventListener('load', function() {console.log('圖片加載完成');});</script>
</body>
6.?submit
?事件
當表單提交時觸發。
<body><form id="myForm"><input type="text" name="username"><input type="submit" value="提交"></form><script>const form = document.getElementById('myForm');form.addEventListener('submit', function(event) {event.preventDefault(); // 阻止表單默認提交行為console.log('表單已提交');});</script>
</body>
?