DOM 事件

151 阅读2分钟

「这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战」。

事件

事件:文档(html 元素及 document)或者浏览器的窗口发生的一些特定的交互瞬间;可以监听这些事件,来实现在事件发生时执行特定的操作;

let btn = document.querySelector('.btn');
let box = document.querySelector('.box');
常见的事件:
  • 鼠标事件:鼠标动作时触发的事件
    • 元素.onclick = function() {} 单击事件
    • 元素.ondbclick = function () {} 双击事件
    • 元素.onmouseenter = function () {} 鼠标移入
    • 元素.onmouseleave = function () {} 鼠标移出
    • 元素.onmouseover = function () {} 鼠标滑过
    • 元素.onmouseout = function () {} 鼠标划出
    • 元素.onmousemove = function () {} 鼠标移动
    • 元素.onmousedown = function () {} 鼠标按下
    • 元素.onmmouseup = function () {} 鼠标抬起
    • 元素.onmousewheel = function () {} 鼠标滚轮滚动
box.onmouseover = function () {
   console.log(1111)
};
box.onmouseout = function () {
   console.log(2222)
};
box.onmousedown = function () {
   console.log('3333')
};
box.onmouseup = function () {
   console.log(4444)
};
box.onmousewheel = function () {
   console.log(555);
};

  • 键盘事件:一般input、textarea、document.body、document、window、
    • 元素.onkeydown = function() {} 键盘按下
    • 元素.onkeyup = function () {} 键盘抬起

document.documentElement 监听键盘事件

let input = document.querySelector('#input');
input.onkeydown = function () {
   console.log('123')
};
document.onkeyup = function () {
   console.log('keyup')
};
window.onkeydown = function () {
   console.log('window key down')
};

  • 表单元素事件
    • onfocus 获取焦点(光标)事件
    • onblur 失去焦点时触发
    • onchange 事件,表单的值(value)发生改变时触发
    • oninput input、textarea 等元素的输入事件
input.onfocus = function () {
   console.log('获取焦点')
};
input.onblur = function () {
   console.log('失去焦点')
};
input.oninput = function () {
   console.log(this.value);
};
  • 系统事件:
    • window.onload 页面中所有的资源全部加载完触发
    • window.onresize 当前窗口尺寸发生改变时触发
    • window.onsroll 滚动条滚动时触发
window.onresize = function () {
   console.log('变了、变了');
};
  • 移动端事件:
    • ontouchstart 触摸元素时触发
    • ontouchend 离开元素时触发
    • ontouchmove 滑动时触发

移动端使用 click 大概有 300ms 的延迟

box.ontouchstart = function () {
   console.log('start');
};
box.ontouchend = function () {
   console.log('end')
};

事件对象

在事件触发时,浏览器传递给事件函数的实参;其中包含了本次事件触发的具体信息;

let box = document.querySelector('.box');
box.onclick = function (e) {
   console.log(e); // MouseEvent e 一般称为事件对象,
   // e.clientX 鼠标点击的位置相对于当前浏览器可视窗口的 左偏移值
   // e.clientY 鼠标点击位置相对于当前浏览器可视窗口的 上偏移值
   // e.pageX 鼠标点击位置相对于 body 左边缘的偏移值
   // e.pageY 鼠标点击位置相对于 body 上边缘的偏移值
   // e.target 触发事件的元素(点击事件中是点击的元素)对象,称为事件源
   // IE 事件触发时把事件信息挂载在 window.event  这个属性上
};
document.onkeydown = function (e) {
   // 键盘事件 KeyboardEvent 
   console.log(e);
   console.log(e.keyCode);
   // e.keyCode 键码:键盘上每个键对应一个键码,当 keydown 事件触发时,
};