事件高级高级

1. 注册事件(绑定事件)

1.1 注册事件概述

给元素添加时间,称为注册事件绑定事件
注册事件两种方式:传统方式和监听注册方式

传统注册方式

  • 利用on开头的时间 onclick
  • <button onclick = "alert()"></button>
  • btn.onclick = function(){}
  • 特点:注册事件的唯一性
  • 同一个元素同一个事件只能设置一个处理函数,最后注册的处理函数会覆盖前面注册的处理函数

方法监听注册

  • w3c标准推荐方式
  • addEventListener()方法
  • IE9以前的IE不支持此方法可用attachEvent()代替
  • 特点:同一个元素同一份事件可以注册多个监听器
  • 按注册顺序依次执行

1.2 addEventLinstener事件监听方式

eventTarget.addEventLinstener(type,listener[,useCapture])
eventTarget.addEventLinstener()方法将指定的监听器注册到eventTarget目标对象上,当该对象触发指定事件时,就会执行事件处理函数
该方法接受的三个参数

  • type:事件类型字符串,比如click、mouseover,注意不要加on
  • listener:事件处理函数,事件发生时,会调用该监听函数
  • useCapture:可选参数,是一个布尔值,默认false。
<!DOCTYPE html>
<html lang="en">

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

<body>
    <button>x方法监听</button>
    <script>
        var btn = document.querySelector("button");
        //addEventListener 里面的时间是字符串不带on
        //同一个事件可以加到同一个元素
        btn.addEventListener('click', function () {
            alert("事件监听")
        })
        btn.addEventListener('click', function () {
            alert("事件监听1")
        })
    </script>
</body>

</html>

1.3 attachEvent事件监听方式(不提倡使用)

eventTarget.attachEvent(eventNameWithOn,callback)
两个参数:

  • eventNameWithOn:事件类型字符串,如onclick、onmouseover,这里带on
  • callback:事件处理函数
//兼容性attachEvent,IE9以前支持独,IE9以后有不兼容会报错
        btns[1].attachEvent('onclick', function () {
            alert("123123")
        })

1.4 注册事件兼容性解决方案

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UVIpgWU0-1632923032016)(vx_images/1262257200967.png)]

2. 删除事件(解绑事件)

2.1 删除事件的方式

  1. 传统方式
    eventTarget.onclick=null
  2. 方法监听注册方式
    1. eventTarget.removeEventListener(type,listener[,useCapture])
    2. eventTarget.detachEvent()
    <!DOCTYPE html>
<html lang="en">

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

<body>
    <div>1</div>
    <div>2</div>
    <div>3</div>

    <script>
        var ds = document.querySelectorAll("div");
        //传统方式删除事件
        ds[0].onclick = function () {
            alert("!1111");
            //只弹出一次
            ds[0].onclick = null;
        }
        function fn() {
            alert("2222");
            ds[1].removeEventListener('click', fn)
        }

        ds[1].addEventListener('click', fn) //fn不需要加小括号
        // ds[1].removeEventListener('click', fn)

        //IE9以前用法
        ds[2].attachEvent('onclick', fn1);
        function fn1() {
            alert("33333");
            ds[2].detachEvent('onclcik', fn1);
        }

    </script>
</body>
</html>

3. DOM事件流

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-d8Me5WV6-1632923032017)(vx_images/5217228180968.png)]
DOM时间流分为3个阶段

  1. 捕获阶段
  2. 当前目标阶段
  3. 冒泡阶段
  • 事件冒泡:IE提出,事件开始时由最具体的元素接受,然后逐级向上传播到DOM最顶层节点的过程
  • 事件捕获:由DOM最顶层节点开始,然后逐级向下传播到最具体的远速速接收的过程。
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CbodKySF-1632923032018)(vx_images/4825234199394.png)]
    注意
  1. JS代码只能捕获或者冒泡其中之一的阶段
  2. onclick和attachEvent只能得到冒泡阶段
  3. addEventListener(type,listener[,useCapture])第三个参数如果是true,表示在事件捕获阶段调用事件处理程序;如果是false(默认),表示在事件冒泡阶段调用事件处理程序。
  4. 实际开发中很少使用事件捕获,更关注事件冒泡
  5. 有些事件没有冒泡如:onblur/onfocus/onmouseenter/onmouseleave
<!DOCTYPE html>
<html lang="en">

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

        .son {
            width: 100px;
            height: 50px;
            margin: auto;
            background-color: blue;
            text-align: center;
            line-height: 50px;
        }
    </style>
</head>

<body>
    <div class="father">
        <div class="son">son盒子</div>
    </div>

    <script>
        //捕获阶段:addEventListener第三个参数是ture 那么处于捕获阶段
        // 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)
        //点击son 先弹出father后弹出son


        //冒泡阶段:addEventListener第三个参数是false或者不写 那么处于冒泡阶段
        // son -> father -> body -> html-> document
        
        var son = document.querySelector(".son");
        son.addEventListener('click', function () {
            alert('son')
        })
        var father = document.querySelector(".father");
        father.addEventListener('click', function () {
            alert('father')
        })
        document.addEventListener('click', function () {
            alert('document');
        })
        // 点击son 先弹出son后弹出father最后出document
    </script>
</body>

</html>

4.事件对象

div.addEventListener('click', function (event) { })
   
div.onclick = function (event) { }
// 这个event就是事件对相 evt或e

事件对象的常见属性和方法

事件对象属性方法说明
e.target返回触发事件的对象 标准
e.srcElement返回触发事件的对象 非标准ie6-8使用
e.type返回事件类型 如click、mouseover等
e.canceBubble该属性阻值冒泡 ie6-8使用
e.returnValue该属性阻值默认时间(默认行为) 非标准 ie6-8使用 如不让连接跳转
e.preventDefault()该方法 阻值默认事件 标准
e.stopPropagation()阻值冒泡 标准
<!DOCTYPE html>
<html lang="en">

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

<body>
    <div>123</div>
    <ul>
        <li>123123</li>
        <li>123123</li>
        <li>123123</li>
    </ul>

    <script>
        //1. e.target返回是触发事件的(对象)元素
        // this返回绑定事件的对象
        var div = document.querySelector('div');
        div.addEventListener('click', function (e) {
            console.log(e.target);
            console.log(this);
        })

        var ul = document.querySelector('ul');
        ul.addEventListener('click', function (e) {
            //我们给ul绑定了事件 this指向ul
            console.log(this);
            //e.target返回点击触发的元素
            console.log(e.target);
        })
    </script>
</body>

</html>

阻值默认行为

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</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. 返回事件类型
        var div = document.querySelector("div");
        div.addEventListener('click', fn);
        div.addEventListener('mouseover', fn);
        div.addEventListener('mouseout', fn);
        function fn(e) {
            console.log(e.type);
        }

        //2. 阻值默认行为  不让链接跳转
        var a = document.querySelector("a");
        // a.addEventListener('click', function (e) {
        //     e.preventDefault();     //dom 标准写法
        // })
        //3. 传统注册方式
        a.onclick = function (e) {
            //普通浏览器
            // e.preventDefault();//方法

            //低版本浏览器
            // e.returnValue;  //属性

            //可以利用 return false 也可阻值默认行为 无兼容性问题
            // 特点:return后的语句不执行
            return false;

        }
    </script>
</body>

</html>

阻止冒泡

事件冒泡:开始时有触发事件向上传播
两种方法

  1. 标准写法stopPropagation()方法
  2. 非标准写法IE6-8使用cancelBubble = true属性
<!DOCTYPE html>
<html lang="en">

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

        .son {
            width: 50px;
            height: 50px;
            margin: auto;
            line-height: 50px;
            text-align: center;
            background-color: blue;
        }
    </style>
</head>

<body>
    <div class="father">
        <div class="son">son</div>
    </div>

    <script>
        var son = document.querySelector(".son");
        son.addEventListener('click', function (e) {
            alert("son");
            //阻值冒泡 标准写法
            // e.stopPropagation();
            //非标准 IE678使用
            e.cancelBubble = true;
        }, false)

        var father = document.querySelector(".father");
        father.addEventListener('click', function () {
            alert('father');
        }, false)

        document.addEventListener('click', function () {
            alert("document");
        })
    </script>
</body>

</html>

6. 事件委托(代理、委派)

事件委托
事件代理,JQuery里称为事件委派
原理
不设置每个子节点的单独事件监听,儿时事件监听器设置在其父节点上,然后利用冒泡原理影响设置每个子节点
作用
只操作一次DOM,提高了程序的性能

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

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

<body>
    <ul>
        <li>点击点击点击01</li>
        <li>点击点击点击02</li>
        <li>点击点击点击03</li>
        <li>点击点击点击04</li>
        <li>点击点击点击05</li>
    </ul>

    <script>
        var ul = document.querySelector("ul");
        ul.addEventListener('click', function (e) {
            // alert('123123');
            //e.target可以得到点击的对象
            e.target.style.backgroundColor = "pink";
            e.target.addEventListener('mouseout', function () {
                this.style.backgroundColor = "";
            })
        })
    </script>
</body>

</html>

7.常用的鼠标事件

常用鼠标事件

鼠标事件触发条件
onclick鼠标点击左键触发
onmouseover鼠标经过触发
onmouseout鼠标离开触发
onfocus获得鼠标焦点触发
onblur失去鼠标焦点触发
onmousemove鼠标移动触发
onmouseup鼠标弹起触发
onmousedown鼠标按下触发
  1. 禁止鼠标右键菜单
    contextmenu主要控制应该何时显示上下文菜单,主要用于程序员取消默认的上下文菜单

    document.addEventListener('contextmenu',function(e){
        e.pareventDefault();
    })
    
  2. 禁止鼠标选中(selectstart 开始选中)

    document.addEventListener('selectstart',function(e){
        e.pareventDefault();
    })
    
<!DOCTYPE html>
<html lang="en">

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

<body>
    不分享
    <script>
        //禁用右键菜单
        document.addEventListener('contextmenu', function (e) {
            e.preventDefault();
        })
        //禁止选中文字
        document.addEventListener('selectstart', function (e) {
            e.preventDefault();
        })
    </script>
</body>

</html>

2. 鼠标事件对象

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

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

<body>
    <script>
        document.addEventListener('click', function (e) {
            //1. client 鼠标在可视区x,y坐标,不随页面滚动而改变
            console.log(e.clientX);
            console.log(e.clientY);
            console.log("------------------");
            //2. page 鼠标在页面x,y坐标,随页面滚动而改变
            console.log(e.pageX);
            console.log(e.pageY);
        })
    </script>
</body>

</html>

案例:跟随鼠标的图片

案例分析

  1. 鼠标不断移动,使用鼠标移动事件
  2. 在页面中移动,给doucument注册事件
  3. 图片要移动距离,而且不占位置,要是用绝对定位
  4. 核心原理:每次鼠标移动,获取新的鼠标坐标给到图片的top和left
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        img {
            position: absolute;
        }
    </style>
</head>

<body>
    <img src="./images/angel.gif" alt="">

    <script>
        var img = document.querySelector("img");
        document.addEventListener('mousemove', function (e) {
            img.style.top = e.pageY - 50 + 'px';
            img.style.left = e.pageX - 30 + 'px';
        })
    </script>
</body>

</html>

8. 常用键盘事件

常用键盘事件

键盘事件触发条件
onkeyup某按键松开时触发
onkeydown某按键按下时触发
onkeypress某按键按下时触发 不识别功能键 ctrl shift 箭头等

三个按键的执行顺序
keydown --> keypress --> keyup

键盘事件对象

键盘事件对象属性说明
keyCode返回该建的ASCII码值

注意

  1. onkeyup和onkeydown不区分按下键的大小写,onkeypress区分大小写
  2. 实际开发中使用 keyup和keydown较多,识别所有按键
  3. keypress不是被功能键,但是keyCode属性能区分大小写,返回不同的ASCII码值

案例模拟京东按键输入内容

当我们按下s光标自动到输入框

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

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

<body>
    <input type="text">
    <script>
        var search = document.querySelector("input");
        document.addEventListener('keyup', function (e) {
            if (e.keyCode == 83) {
                search.focus();
            }
        })
    </script>
</body>

</html>

案例 放大输入内容

当在输入框输入内容是,放大内容

  1. 输入时 上面的打好盒子显示大号字体
  2. 表单检测用户输入,给表单参加键盘事件
  3. 把表单的值获取 给到盒子体
  4. 输入框为空 则自动隐藏大盒子
  5. 注意
    1.keyup和keydown在文本框中的特点:他们两个事件处罚的时候,文字还没有落入文本框中。
    2. keyup触发时,文字已经落入文本框里了
  6. 当失去焦点隐藏盒子
  7. 当获得焦点并且文本框不为空,就显示
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .search {
            position: relative;
            width: 178px;
            margin: 100px;
        }

        .con {
            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"></div>
        <input type="text" placeholder="请输入您的快递单号" class="jd">
    </div>

    <script>
        //输入时 上面的打好盒子显示大号字体
        // 表单检测用户输入,给表单参加键盘事件
        // 把表单的值获取 给到盒子体
        // 输入框为空 则自动隐藏大盒子
        var con = document.querySelector(".con");
        var inp = document.querySelector('.jd');
        inp.addEventListener('keyup', function () {
            if (inp.value != "") {
                con.innerText = this.value;
                con.style.display = "block";
            } else {
                con.style.display = "none";
            }
        })
        //当失去焦点 隐藏盒子
        inp.addEventListener('blur', function () {
            con.style.display = 'none';
        })
        //当获得焦点 显示盒子
        inp.addEventListener('focus', function () {
            if (this.value != "") {
                con.style.display = 'block';
            }
        })
    </script>

</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值