2025.4.22学习日记 JavaScript的常用事件
在 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>