JS DOM events

1. Event overview

  1. Add events to elements, called registration events or binding events
  2. There are two ways to register events: the traditional way and the way to monitor the registration method
  • Traditional registration method:
    1. onclick
    2. Features: uniqueness of registration events
    3. Only one handler function can be set for the same event on the same element, and the last registered handler function will overwrite the previously registered handler function
  • Method listener registration event
    1. w3c standard recommended way
    2. addEventListener() method
    3. IE before IE9 does not support this method, you can use attachEvent() instead
  1. DOM event stream
  • Event flow describes the order in which events are received from pages
  • When an event occurs, it will propagate among the element nodes in a specific order. This propagation process is the DOM event flow
  • DOM event flow is divided into 3 phases
    1. capture phase
    2. current target stage
    3. bubbling stage
  • Notice:
    1. Only one of capturing or bubbling can be executed in JS code.
    2. onclick and attachEvent (ie) only get the bubbling phase.
    3. If the third parameter of addEventListener is true, then it is in the capture phase document -> html -> body -> father -> son If the third parameter of addEventListener is false or omitted, then it is in the bubbling phase son -> father -> body - > html -> document
    4. Actual development rarely uses event capture and pays more attention to event bubbling
    5. Some events do not bubble, such as onblur onfocus onmouseenter onmouseleave
    6. Event bubbling sometimes causes trouble, and sometimes helps to do certain events very cleverly

2. Two ways to register events

2.1 Traditional way to register events

2.2 Event listener registration event addEventListener

(1) The event type inside is a string must be quoted and without on
(2) Multiple listeners (event handlers) can be added to the same element and the same event

2.3 attachEvent Previous versions of ie9 support

<!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>传统注册事件</button>
    <button>方法监听注册事件</button>
    <button>attachEvent</button>
    <script>
        var btns = document.querySelectorAll('button');
        //1.传统方式注册事件
        btns[0].onclick = function(){
      
      
            alert('hi');
        }
        btns[0].onclick = function(){
      
      
            alert('how are you');
        }
        //2.事件监听注册事件 addEventListener 
        
        btns[1].addEventListener('click',function(){
      
      
            alert(22);
        })
        btns[1].addEventListener('click',function(){
      
      
            alert(44);
        })
        //3.attachEvent ie9以前的版本支持
        btns[2].attachEvent('onclick',function(){
      
      
            alert(11);
        })
    </script>
</body>
</html>

3. Delete event

3.1 Delete events in the traditional way

3.2 removeEventListener delete event

3.3 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: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <script>
        var divs = document.querySelectorAll('div');
        divs[0].onclick = function(){
      
      
            alert(11);

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

4. Event object

  1. event is an event object written in the parentheses of our listener function as a formal parameter
  2. The event object exists only when there is an event. It is automatically created by the system for us and does not require us to pass parameters.
  3. The event object is a collection of a series of related data related to our event. For example, the mouse click contains the relevant information of the mouse, the mouse coordinates, and if it is a keyboard event, it contains the information of the keyboard event, such as judging whether the user has pressed the button. that key
  4. We can name this event object by ourselves, such as event, evt, e
  5. Event objects also have compatibility issues ie678 through window.event Compatibility writing e = e || window.event;
<!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: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div>123</div>
    <script>
        //事件对象
        var div = document.querySelector('div');
        div.onclick = function(e){
      
      
            console.log(e);
            console.log(window.event);
            e = e || window.event;
            console.log(e);
        } 
        /* div.addEventListener('click',function(e){
            console.log(e);
        }) */
    </script>
</body>
</html>

5. Event object e.target

<!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: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div>123</div>
    <ul>
        <li>abc</li>
        <li>abc</li>
        <li>abc</li>
    </ul>
    <script>
        // 常见事件对象的属性和方法
        // 1.e.target 返回的是触发事件的对象(元素) this 返回的是绑定事件的对象(元素)
        // 区别: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 指向我们点击的那个对象 谁触发了这个事件 我们点击的是li e.target指向的就是li
            console.log(e.target);
        })

        // div.onclick = function(e){
      
      
        //     e = e || window.event;
        //     var target = e.target || e.srcElement;
        //     console.log(target);
        // }
        // 2.了解 跟this 有个非常相似的属性 currentTarget  ie678不认识
    </script>
</body>
</html>

6. Event objects prevent default behavior

<!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>

    </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.返回事件类型
        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.preventDefault();
            // 低版本浏览器 ie678 returnValue 属性
            // e.returnValue;
            // 我们可以利用return false 也能阻止默认行为 没有兼容性问题
            return false;
            alert(11);
        }
    </script>
</body>
</html>

7. Prevent event bubbling

 <div class="father">
        <div class="son">son儿子</div>
    </div>
    <script>
        // 常见事件对象的属性和方法
        // 阻止冒泡  dom 推荐的标准 stopPropagation() 
        var son = document.querySelector('.son');
        son.addEventListener('click', function(e) {
      
      
            alert('son');
            e.stopPropagation(); // stop 停止  Propagation 传播
            e.cancelBubble = true; // 非标准 cancel 取消 bubble 泡泡
        }, false);
    </script>

8. Event delegation

  • The core principle of event delegation: add a listener to the parent node, and use event bubbling to affect each child node
  • By setting the listener of ul, and then through event bubbling, it can affect li
<script>
        var ul = document.querySelector('ul');
        ul.addEventListener('click',function(e){
      
      
            //alert('知否知否,时刻提防');
            // e.target 这个可以得到我们点击的对象
            e.target.style.backgroundColor = 'pink';
        })
    </script>

9. Common mouse events

<script>
        //1.contextmenu 可以禁用右键菜单
        document.addEventListener('contextmenu',function(e){
      
      
            e.preventDefault();
        })
        //2.禁止选中文字 selectstart
        document.addEventListener('selectstart',function(e){
      
      
            e.preventDefault();
        })
    </script>

10. Mouse event object

<script>
        //鼠标事件对象 MouseEvent
        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);
            console.log('---------------------');

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

11. Common keyboard events

<script>
        //常用的键盘事件
        //1.keyup 按键弹起的时候触发
        // document.onkeyup = function(){
      
      
        //     console.log('我弹起了');
        // }
        document.addEventListener('keyup',function(){
      
      
            console.log('我弹起了');
        })
        //2.keydown 案件按下的时候触发
        document.addEventListener('keydown',function(){
      
      
            console.log('我按下了');
        })
        //3.keypress 按键按下的时候触发 不能识别功能键 比如 ctrl shift 左右箭头等
        document.addEventListener('keypress', function() {
      
      
                console.log('我按下了press');
        })
        //三个事件执行的顺序是:keydown->keypress->keyup
    </script>

12. Keyboard event keyCode attribute

<script>
         // 键盘事件对象中的keyCode属性可以得到相应键的ASCII码值
         //1.我们的keyup 和 keydown事件不区分字母大小写 
         // 2. 我们的keypress 事件 区分字母大小写  a  97 和 A 得到的是65
         document.addEventListener('keyup',function(e){
      
      
             //console.log(e);
             console.log(e.keyCode);
             
             // 我们可以利用keycode返回的ASCII码值来判断用户按下了那个键
             if(e.keyCode == 65){
      
      
                 alert('您按下了a键');
             }else{
      
      
                alert('您没有按下a键');
             }
         })
         document.addEventListener('keypress',function(e){
      
      
             //console.log(e);
             console.log(e.keyCode);
         })
    </script>

Guess you like

Origin blog.csdn.net/crush_oo/article/details/124986895