【DOM笔记四】事件高级!(注册/删除事件、DOM事件流、事件对象、事件委托、鼠标 / 键盘事件、相关案例)

发布时间:2023年12月20日

7 事件高级

7.1 注册事件概述

给元素添加事件,称为注册事件或者绑定事件

注册事件有两种方式传统方式方法监听注册方式

  1. 传统注册方式on开头
  • on开头的事件:onclick
  • <button onclick = “alert(‘hi~’)”></button>
  • btn.onclick = function{}
  • 特点:注册事件的唯一性(同一个元素同一个事件只能设置一个处理函数)
  1. 方法监听注册方式addEventListener()
  • w3c标准(推荐)
  • addEventListener()方法(IE9以前为attachEvent()
  • 特点:同一个元素同一个事件可以注册多个监听器(监听处理函数function),按注册顺序依次执行
eventTarget.addEventListener(type, listener, useCapture)

将指定的监听器注册到eventTarget(目标对象)上,当该对象触发指定的事件时,就会执行事件处理函数,涉及到的参数为:

  • type:事件类型为字符串,比如’click’、‘mouseover’,注意这里不要带on
  • listener:事件处理函数,事件发生时,会调用该监听函数
  • useCapture:可选参数,是一个布尔值,默认是false(冒泡阶段,true是捕获阶段)
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <button>传统注册事件</button>
    <button>方法监听注册事件</button>
    <button>ie9 attachEvent</button>
    <script>
        var btns = document.querySelectorAll('button');
        // 1. 传统方式注册事件 onclick
        btns[0].onclick = function() {
        	alert('hi');
        }
        btns[0].onclick = function() {
        	alert('hao a u');    // 第二个监听器会覆盖第一个,传统方法要保证唯一性
        }
        
        // 2. 事件侦听注册事件 addEventListener 
        btns[1].addEventListener('click', function() {    // 事件类型是字符串 必定加引号 而且不带on
        	alert(22);
        })
        btns[1].addEventListener('click', function() {    // 可以添加多个监听器(事件处理程序)
        	alert(33);
        })
        
        // 3. attachEvent ie9以前的版本支持
        btns[2].attachEvent('onclick', function() {
        	alert(11);
        })
    </script>
</body>

</html>

7.2 删除事件

  1. 传统注册方式

    eventTarget.onclick = null;

  2. 方法监听注册方式

    eventTarget.removeEventListener(type, listener, useCapture);

    eventTarget.detachEvent(eventNameWithOn, callback);

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <script>
        var divs = document.querySelectorAll('div');
        // 1. 传统方式删除事件
        divs[0].onclick = function() {
                alert(11);
                divs[0].onclick = null;  //效果:弹出一次11后,再次点击就不再弹出11了,解绑该事件
        }

        // 2. removeEventListener
        divs[1].addEventListener('click', fn)  // 调用fn
        function fn() {
            alert(22);
            divs[1].removeEventListener('click', fn);  // 删除事件(里面的fn不需要调用加小括号)
        }
        
        // 3. detachEvent
        divs[2].attachEvent('onclick', fn1);
        function fn1() {
            alert(33);
            divs[2].detachEvent('onclick', fn1);
        }
    </script>
</body>

</html>

7.3 DOM事件流

  • 事件流: 从页面中接收事件的顺序
  • DOM 事件流:事件发生时会在元素节点之间按照特定的顺序传播传播过程

比如我们给一个div注册了点击事件:

image-20231220105752358

DOM 事件流分为3个阶段:

  1. 捕获阶段
  2. 当前目标阶段
  3. 冒泡阶段(更常用):onclick 和 attachEvent(ie) 只能得到冒泡阶段。onblur、onfocus、onmouseenter、onmouseleave 没有冒泡阶段。
  • 事件捕获:网景最早提出,由 DOM 最顶层节点开始,然后逐级向下传播到到最具体的元素接收的过程。
  • 事件冒泡:IE 最早提出,事件开始时由最具体的元素接收,然后逐级向上传播到到 DOM 最顶层节点的过程。
  • JS代码中只能执行捕获或者冒泡其中的一个阶段。
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .father {
            overflow: hidden;
            width: 300px;
            height: 300px;
            margin: 100px auto;
            background-color: pink;
            text-align: center;
        }
        
        .son {
            width: 200px;
            height: 200px;
            margin: 50px;
            background-color: purple;
            line-height: 200px;
            color: #fff;
        }
    </style>
</head>

<body>
    <div class="father">
        <div class="son">son盒子</div>
    </div>
    <script>
        // 1. 捕获阶段 如果addEventListener第三个参数是 true 那么处于捕获阶段  document -> html -> body -> father -> son
        var son = document.querySelector('.son');
        son.addEventListener('click', function() {
            alert('son');
        }, true);
        var father = document.querySelector('.father');
        father.addEventListener('click', function() {
            alert('father');
        }, true);    // 效果:先弹出father,再弹出son
        
        // 2. 冒泡阶段 如果addEventListener第三个参数是false或者不填 那么处于冒泡阶段  son -> father ->body -> html -> document
        var son = document.querySelector('.son');
        son.addEventListener('click', function() {
            alert('son');
        }, false);
        var father = document.querySelector('.father');
        father.addEventListener('click', function() {
            alert('father');
        }, false);
        document.addEventListener('click', function() {
            alert('document');
        })       // 效果:先弹出son,再弹出father,最后弹出document。(只能执行捕获或者冒泡其中的一个阶段,后面的冒泡阶段会覆盖前面的捕获阶段)
    </script>
</body>

</html>

7.4 事件对象

eventTarget.onclick = function(event) {}

eventTarget.addEventListener('click', function(event) {})

  • 这里 event 就是事件对象,相当于形参,我们还喜欢的写成 e 或者 evt
  • event对象代表**事件的状态**,比如键盘按键的状态、鼠标的位置、鼠标按钮的状态
  • 事件发生后,**跟事件相关的一系列信息数据的集合**都放到这个对象里面,这个对象就是事件对象 event,它有很多属性和方法。

常用的属性和方法:

image-20231220114621312

e.target 和 this 的区别:

  • this :返回绑定事件的元素, 这个函数的调用者,绑定的谁
  • e.target :返回触发事件的元素,点击的谁
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div>123</div>
    <ul>
        <li>abc</li>
        <li>abc</li>
        <li>abc</li>
    </ul>
    <script>
        // `e.target`返回点击的谁,`this`返回绑定的谁
        var div = document.querySelector('div');
        div.addEventListener('click', function(e) {
            console.log(e.target);   // 触发事件的元素,返回<div>123</div>
            console.log(this);   // 绑定事件的元素,返回<div>123</div>
        })
        
        var ul = document.querySelector('ul');
        ul.addEventListener('click', function(e) { 
            console.log(this);   // 绑定事件的元素,返回<ul>...</ul>
            console.log(e.target);  // 触发事件的元素,返回<li>abc</li>
		})
    </script>
</body>

</html>
  • e.type 返回是事件的类型
  • e.preventDefault(),阻止默认行为(事件)
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>

    </style>
</head>

<body>
    <div>123</div>
    <a href="http://www.baidu.com">百度</a>
    <form action="http://www.baidu.com">
        <input type="submit" value="提交" name="sub">
    </form>
    <script>
        // 常见事件对象的属性和方法
        // 1. `e.type`返回事件类型
        var div = document.querySelector('div');
        div.addEventListener('click', fn);
        div.addEventListener('mouseover', fn);
        div.addEventListener('mouseout', fn);
        function fn(e) {
            console.log(e.type);  // mouseover click mouseout(显示当前发生的事件类型)
        }
        
        // 2. 阻止默认行为(事件) 例如:让链接不跳转/让提交按钮不提交
        var a = document.querySelector('a');
        a.addEventListener('click', function(e) {
            e.preventDefault();   // dom 标准写法
        })
            
        // 3. 传统的注册方式
        a.onclick = function(e) {
            // 普通浏览器 e.preventDefault();  方法
            // e.preventDefault();
            // 低版本浏览器 ie678  returnValue  属性
            // e.returnValue;
            // return false也能阻止默认行为,没有兼容性问题。
            return false;
            alert(11);   // return 后面的代码不执行了
        }
    </script>
</body>

</html>
  • e.stopPropagation(),阻止事件冒泡(推荐)
<script>
    var son = document.querySelector('.son');
    son.addEventListener('click', function(e) {
        alert('son');
        e.stopPropagation(); // 标准 stop停止 Propagation传播
        e.cancelBubble = true; // 非标准(IE6-8) cancel取消 bubble泡泡
    }, false);  // false:冒泡阶段

    var father = document.querySelector('.father');
    father.addEventListener('click', function() {
        alert('father');   // 点击盒子后只弹出son,不弹出father和document
    }, false);
    document.addEventListener('click', function() {
        alert('document');
    })
</script>

7.5 事件委托

  • 原理: 不是每个子节点单独设置事件监听器,而是事件监听器设置在其父节点上,然后利用冒泡原理影响其每个子节点
  • 例子: 给 ul 注册点击事件,然后利用事件对象的 target 来找到当前点击的 li,因为点击 li,事件会冒泡到 ul 上, ul 有注册事件,就会触发事件监听器。
  • 作用: 我们只操作了一次 DOM ,提高了程序的执行效率
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <ul>
        <li>知否知否,点我应有弹框在手!</li>
        <li>知否知否,点我应有弹框在手!</li>
        <li>知否知否,点我应有弹框在手!</li>
        <li>知否知否,点我应有弹框在手!</li>
        <li>知否知否,点我应有弹框在手!</li>
    </ul>
    <script>
        // 事件委托的核心原理:给父节点添加侦听器,利用事件冒泡影响每一个子节点
        var ul = document.querySelector('ul');
        ul.addEventListener('click', function(e) {
            alert('知否知否,点我应有弹框在手!');  // 点li就会出现弹框
            e.target.style.backgroundColor = 'pink';  // e.target可以得到我们点击的哪个小li,哪个小li背景就变粉
        })
    </script>
</body>

</html>

7.6 鼠标事件

7.6.1 常用的鼠标事件

image-20231220134049911

1. 禁止鼠标右键菜单

contextmenu主要控制应该何时显示上下文菜单,主要用于取消默认的上下文菜单

document.addEventListener('contextmenu', function(e) {
	e.preventDefault();
})

2. 禁止鼠标选中selectstart 开始选中)

document.addEventListener('selectstart', function(e) {
	e.preventDefault();
})

例子:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    我是一段不愿意分享的文字
    <script>
        // 1. 禁用右键菜单 contextmenu 
        document.addEventListener('contextmenu', function(e) {
            e.preventDefault();
        })
        
        // 2. 禁止选中文字 selectstart
        document.addEventListener('selectstart', function(e) {
            e.preventDefault();
        })
    </script>
</body>

</html>
7.6.2 鼠标事件对象
  • event对象 代表事件的状态,跟事件相关的一系列信息的集合
  • MouseEvent 鼠标事件对象
  • KeyboardEvent 键盘事件对象

image-20231220142502048

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        body {
            height: 3000px;
        }
    </style>
</head>

<body>
    <script>
        // 鼠标事件对象 MouseEvent
        document.addEventListener('click', function(e) {  // MouseEvent {属性:属性值...(鼠标点击的x,y坐标、which按的鼠标左键还是右键...)}
            // 1. client 鼠标在可视区的x和y坐标
            console.log(e.clientX);  // 51:距离可视区左侧51px
            console.log(e.clientY);  // 58:距离可视区上侧58px

            // 2. page 鼠标在页面文档的x和y坐标(更常用)
            console.log(e.pageX);  // 50:距离页面文档左侧51px
            console.log(e.pageY);  // 1328:距离页面文档上侧58px

            // 3. screen 鼠标在电脑屏幕的x和y坐标
            console.log(e.screenX);
            console.log(e.screenY);
        })
    </script>
</body>

</html>

案例:小天使logo一直跟着鼠标走(mousemove)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        img {
            position: absolute;   /* 绝对定位:图片要移动距离,而且不占位置 */
        }
    </style>
</head>

<body>
    <img src="images/angel.gif" alt="">
    <script>
        var pic = document.querySelector('img');
        document.addEventListener('mousemove', function(e) {   // 在页面中移动,给document注册事件,同时,mousemove只要我们鼠标移动1px 就会触发这个事件
            var x = e.pageX;  // pageX鼠标在页面中的X坐标
            var y = e.pageY;
            // console.log('x坐标是' + x, 'y坐标是' + y);
            pic.style.left = x - 50 + 'px';  // x和y坐标做为图片的top和left值就可以移动图片,同时添加px单位
            pic.style.top = y - 40 + 'px';  // 40是图片的高,不减值鼠标就对齐图片的左上角
        });
    </script>
</body>

</html>

7.7 键盘事件

7.7.1 常用的键盘事件

image-20231220144017530

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 常用的键盘事件
        // 1. keyup 按键弹起的时候触发 
        // 传统方法
        // document.onkeyup = function() {
        //      console.log('我弹起了');
        // }
        // 
        document.addEventListener('keyup', function() {
            console.log('我弹起了');
        })

        // 2. keypress 按键按下的时候触发,不能识别功能键(ctrl/shift/左右箭头)
        document.addEventListener('keypress', function() {
            console.log('我按下了press');
        })
        
        // 3. keydown 按键按下的时候触发,能识别功能键
        document.addEventListener('keydown', function() {
            console.log('我按下了down');
        })
        
        // 4. 三个事件的执行顺序  keydown -- keypress -- keyup
    </script>
</body>

</html>
7.7.2 键盘事件对象
  • 更多的使用keydownkeyup, 它能识别所有的键(包括功能键)
  • Keypress不识别功能键,但是keyCode属性能区分大小写,返回不同的ASCII值

image-20231220145647691
image-20231220145437821

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 1. 我们的keyup 和keydown事件不区分字母大小写  a 和 A 得到的都是65
        // 2. 我们的keypress 事件 区分字母大小写  a  97 和 A 得到的是65
        document.addEventListener('keyup', function(e) {
            console.log(e);  // 按下1,返回KeyboardEvent{key:"1",keyCode:49...}
            console.log('up:' + e.keyCode);  // 按下a/A返回65(不区分大小写),返回用户按下键的ASCII码值
            if (e.keyCode === 65) {
                alert('您按下的A键');
            } else {
                alert('您没有按下A键')
            }
        })
        
        document.addEventListener('keypress', function(e) {
            console.log('press:' + e.keyCode);  // 按下a返回97,A返回65(区分大小写)
        })
    </script>
</body>

</html>

案例1:按下S键就把光标定位到搜索框

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <input type="text">
    <script>
        var search = document.querySelector('input');
        document.addEventListener('keyup', function(e) {  // keydown导致按下后一直触发,内容会跑到搜索框里,因此要使用keyup
            // console.log(e.keyCode);  查询S的ASCII码值是多少
            if (e.keyCode === 83) {  // keyCode 判断用户按下的是否是s键
                search.focus();  // 搜索框获得焦点用focus()方法
            }
        })
    </script>
</body>

</html>

案例2:输入快递单号

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .search {   /* 最大的盒子 */
            position: relative;
            width: 178px;
            margin: 100px;
        }
        
        .con {     /* .search中,上面的,字体放大后的盒子 */
            display: none;   /* 原本看不见,输入内容后才可见 */
            position: absolute;
            top: -40px;
            width: 171px;
            border: 1px solid rgba(0, 0, 0, .2);
            box-shadow: 0 2px 4px rgba(0, 0, 0, .2);
            padding: 5px 0;
            font-size: 18px;
            line-height: 20px;
            color: #333;
        }
        
        .con::before {    /* 小三角形 */
            content: '';
            width: 0;
            height: 0;
            position: absolute;
            top: 28px;
            left: 18px;
            border: 8px solid #000;
            border-style: solid dashed dashed;
            border-color: #fff transparent transparent;
        }
    </style>
</head>

<body>
    <div class="search">
        <div class="con">123</div>
        <input type="text" placeholder="请输入您的快递单号" class="jd">
    </div>
    <script>
        var con = document.querySelector('.con');
        var jd_input = document.querySelector('.jd');
        jd_input.addEventListener('keyup', function() {
            // console.log('输入内容啦');  表单中输入几次就返回几次
            if (this.value == '') {
                con.style.display = 'none';   // 内容为空则隐藏
            } else {
                con.style.display = 'block';   // 本来是`display: none;`,显示后鼠标离开记得隐藏
                con.innerText = this.value;  // `this.value`为当前输入的值,赋值给con
            }
        })
            
        // 当我们失去焦点,隐藏这个con盒子
        jd_input.addEventListener('blur', function() {
            con.style.display = 'none';
        })
            
        // 当我们获得焦点,显示这个con盒子
        jd_input.addEventListener('focus', function() {
            if (this.value !== '') {   // 里面有内容才显示con
                con.style.display = 'block';
            }
        })
    </script>
</body>

效果:image-20231220153455498

文章来源:https://blog.csdn.net/waski/article/details/135111563
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。