addEventListener相对于直接使用onXX去注册或监听事件,可以注册多个相同类型的事件处理程序,而不会覆盖现有的处理程序。
一下是默认的addEventListener常用的API
addEventListener的第三个参数
element.addEventListener('click', handleClick, { once: true });
capture:布尔值,表示该监听器是否在捕获阶段执行,默认为false。once:布尔值,表示该监听器是否只执行一次,默认为false。passive:布尔值,表示该监听器是否不会调用preventDefault()方法,默认为false。signal:AbortSignal对象,表示允许使用AbortController中止事件监听器的执行。mozSystemGroup:布尔值,表示该监听器是否在Firefox OS系统组中注册(已弃用)。mozAnon:布尔值,表示该监听器是否匿名(已弃用)。mozAutoPopup:布尔值,表示是否允许Firefox自动弹出相关内容(已弃用)。mozFocusAsync:布尔值,表示是否启用异步焦点处理(已弃用)。
鼠标事件
click:用户单击鼠标时触发的事件。
const button = document.querySelector('button');
button.addEventListener('click', () => {
console.log('Button clicked!');
});
mouseenter 和 mouseleave:鼠标进入或离开元素时触发的事件。
const box = document.querySelector('.box');
box.addEventListener('mouseenter', () => {
console.log('Mouse entered the box!');
});
box.addEventListener('mouseleave', () => {
console.log('Mouse left the box!');
});
mousedown、mouseup 和 mousemove:用户按下或释放鼠标按钮时触发的事件,以及鼠标移动时触发的事件。
const box = document.querySelector('.box');
box.addEventListener('mousedown', () => {
console.log('Mouse button pressed inside the box!');
});
box.addEventListener('mouseup', () => {
console.log('Mouse button released inside the box!');
});
box.addEventListener('mousemove', () => {
console.log('Mouse moved inside the box!');
});
mouseover 和 mouseout:鼠标进入或离开元素的边界时触发的事件。
const box = document.querySelector('.box');
box.addEventListener('mouseover', () => {
console.log('Mouse over the box!');
});
box.addEventListener('mouseout', () => {
console.log('Mouse out of the box!');
});
wheel :鼠标滚轮滚动时触发的事件。
const box = document.querySelector('.box');
box.addEventListener('wheel', (event) => {
console.log(`Mouse wheel scrolled ${event.deltaY}px!`);
});
键盘事件
keydown、keyup 和 keypress:用户按下或释放键盘上的按键时触发的事件,以及在持续按下时重复触发的事件。
document.addEventListener('keydown', (event) => {
console.log(`Key pressed: ${event.key}`);
});
document.addEventListener('keyup', (event) => {
console.log(`Key released: ${event.key}`);
});
document.addEventListener('keypress', (event) => {
console.log(`Key pressed and held: ${event.key}`);
});
表单监听
submit 和 reset:表单提交和重置时触发的事件。
<form>
<input type="text" name="name"><br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
<script>
const form = document.querySelector('form');
form.addEventListener('submit', () => {
console.log('Form submitted!');
});
form.addEventListener('reset', () => {
console.log('Form reset!');
});
</script>
focus 和 blur:元素获得或失去焦点时触发的事件。
<input type="text" name="name">
<script>
const input = document.querySelector('input');
input.addEventListener('focus', () => {
console.log('Input focused!');
});
input.addEventListener('blur', () => {
console.log('Input lost focus!');
});
</script>
change 和 input:元素值改变时触发的事件,例如输入框中文本的更改。
<input type="text" name="name">
<script>
const input = document.querySelector('input');
input.addEventListener('focus', () => {
console.log('Input focused!');
});
input.addEventListener('blur', () => {
console.log('Input lost focus!');
});
</script>
窗口事件
load 和 unload:文档加载和卸载时触发的事件。
window.addEventListener('load', () => {
console.log('Document loaded!');
});
window.addEventListener('unload', () => {
console.log('Document unloaded!');
});
设备方向变化事件(deviceorientation、devicemotion)
<script>
window.addEventListener('deviceorientation', (event) => {
console.log(`Device orientation changed: alpha=${event.alpha}, beta=${event.beta}, gamma=${event.gamma}`);
});
window.addEventListener('devicemotion', (event) => {
console.log(`Device motion detected: acceleration=${event.acceleration}, accelerationIncludingGravity=${event.accelerationIncludingGravity}, rotationRate=${event.rotationRate}, interval=${event.interval}`);
});
</script>
元素事件
剪贴板事件(cut、copy、paste):
<input type="text" id="input" />
<script>
const input = document.getElementById('input');
input.addEventListener('cut', (event) => {
console.log('Text cut!');
});
input.addEventListener('copy', (event) => {
console.log('Text copied!');
});
input.addEventListener('paste', (event) => {
console.log('Text pasted!');
});
</script>
拖放事件(dragstart、dragend、dragenter、dragover、dragleave、drop):
<div id="box" draggable="true">Drag me!</div>
<div id="dropzone">Drop here!</div>
<script>
const box = document.getElementById('box');
const dropzone = document.getElementById('dropzone');
box.addEventListener('dragstart', (event) => {
console.log('Box dragged!');
});
box.addEventListener('dragend', (event) => {
console.log('Box drag ended!');
});
dropzone.addEventListener('dragenter', (event) => {
event.preventDefault(); // 防止默认行为发生
console.log('Box dragged into the dropzone!');
});
dropzone.addEventListener('dragover', (event) => {
event.preventDefault(); // 防止默认行为发生
console.log('Box being dragged over the dropzone!');
});
dropzone.addEventListener('dragleave', (event) => {
console.log('Box dragged out of the dropzone!');
});
dropzone.addEventListener('drop', (event) => {
event.preventDefault(); // 防止默认行为发生
console.log('Box dropped on the dropzone!');
});
</script>
动画事件(animationstart、animationend、animationiteration):
<div id="box">Animate me!</div>
<style>
#box {
width: 50px;
height: 50px;
background-color: red;
animation-name: example;
animation-duration: 2s;
animation-iteration-count: infinite;
}
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
</style>
<script>
const box = document.getElementById('box');
box.addEventListener('animationstart', (event) => {
console.log('Animation started on the box!');
});
box.addEventListener('animationend', (event) => {
console.log('Animation ended on the box!');
});
box.addEventListener('animationiteration', (event) => {
console.log('Animation iteration on the box!');
});
</script>
过渡事件(transitionend):
<div id="box">Transition me!</div>
<style>
#box {
width: 50px;
height: 50px;
background-color: red;
transition-property: background-color;
transition-duration: 2s;
}
#box:hover {
background-color: yellow;
}
</style>
<script>
const box = document.getElementById('box');
box.addEventListener('transitionend', (event) => {
console.log('Transition ended on the box!');
});
</script>
注意:动画监听可能有兼容性问题,可以这样写
/**
* Listening to animation end function
* @param el - element
* @param fun - Execute Function
*/
export function onTransitionEndEvent(el: HTMLElement, fun: Function) {
let transitionsName: string | null = null
const transitions: { [key in string]: string } = {
transition: 'transitionend',
OTransition: 'oTransitionEnd',
MozTransition: 'transitionend',
WebkitTransition: 'webkitTransitionEnd'
}
for (const t in transitions) {
if (el.style[t as any] !== undefined) {
transitionsName = transitions[t]
break
}
}
if (!transitionsName) {
fun()
} else {
const transitionFun = () => {
fun()
el.removeEventListener(transitionsName as string, transitionFun)
}
el.addEventListener(transitionsName, transitionFun)
}
}