Home  >  Article  >  Web Front-end  >  Event analysis of DOM in javascript (with code)

Event analysis of DOM in javascript (with code)

不言
不言Original
2018-09-04 10:20:031163browse

What is the event? What's the use of events? This article will share with you the event analysis of DOM in JavaScript, and introduce the concept of events and the usage of events.

Event

##1. What is the event

Let JS know the user behavior of the program, such as the user clicking on HTML A certain button on the page and the user inputting the user name and password

 <script>
        var button = document.getElementById('btn');
//        获取按钮元素
        button.onclick = function () {
//        事件绑定
            console.log('你已点了我');
        }
    </script>

2. Register eventThe JS function is associated with the specified event, and the bound function becomes the event's When the handle
event is fired, the bound function will be called

The event attribute of the HTML element

represents the actual registration event function

This method does not effectively separate the structure and behavior of HTML

<body>
<button onclick="mylove()" id="btn">按钮</button>
<script>
    function mylove() {
        console.log('你已点了我');
    }
</script>
</body>

Event attributes of the DOM object

Locate the Document object in THML page element

and returns the DOM object body attribute, through which various registration event functions are implemented

<body>
<button id="btn">按钮</button>
<script>
    var btn = document.getElementById('btn');
    btn.onclick = mylove;
    function mylove() {
        console.log('你已点了我');
    }
</script>
</body>

Event listener

to addEvantLisener() method, calling this method means that the element adds an event listener

body>
<button id="btn">按钮</button>
<script>
    var btn = document.getElementById('btn');
    btn.attachEvent('onclick',function () {
        console.log('XXX');
    })
    function bind(element,eventName, functionName) {
        if (element.addEventListener) {
            element.addEventListener()
        }
    }
</script>

</body>

This

Use the addEventListener() method in the event listener When registering an event for a page, this refers to the registered event element

When using the attachEent() method to register an event for the page, this refers to the Window object, not the registered event

<script>
    var qyc =document.getElementById('qyc');
    /*qyc.addEventListener('click',function () {
        console.log(this);//this指当前绑定事件的元素
    });*/
    /*qyc.attachEvent('onclick',function () {
        console.log(this);//this指当前环境的全局对象(Window对象)
    });*/
    bind(qyc,'click',function () {
        console.log(this);//在不同的浏览器中,this会有不同的表示
    });
    function bind(element, eventName, functionName) {
        if (element.addEventListener) {
        } else {
            element.attachEvent('on' + eventName, function () {
                functionName.call(element)

            });
        }
    }//此为IE8之前的版本兼容的解决方案
</script>
</body>

3. Remove Register event

removeEventListener() method, call this method to indicate element removal event listener

<body>
<button id="qyc">按钮</button>
<script>
    var qyc = document.getElementById('qyc');
    function mylove() {
        console.log('XXX');
    }
    qyc.addEventListener('click',mylove);
    qyc.addEventListener('click',function () {
        console.log('YYY');
    });
    qyc.removeEventListener('click',mylove);
    function unbind(element,eventName,functionName) {
        if (element.removeEventListener) {
            element.removeEventListener(eventName, functionName);
        }else {
            element.detachEvent('on' + eventName, functionName);
        }
    }
</script>
</body>

4, Event event object

Indicates that removing registered events in versions prior to IE8

browsers do not support the removeEventListener() method

<body>
<button id="qyc" onclick="mylove(event)">按钮</button>
<script>
    var qyc = document.getElementById('qyc');
    qyc.addEventListener('click',function (event) {
        console.log(event);
    });
    qyc.attachEvent('onclick',function () {
        console.log(window.event);
    });

    function bind(element,eventName, functipnName) {
        if (element.addEventListener){
            element.addEventListener(eventName,functipnName)
        } else {
          element.attachEvent('on' + eventName, function(){
             functipnName.call(element);
          });
        }
    }
</script>

5. Get the target

Event event object provides the target attribute , Get the HTML element that triggered the current event

Event event object provides the currentTarget attribute, get the HTML element that registered the current event

<style>
        ul {
           background-color: red;
        }
        #wl {
           background-color: blue;
        }
        a {
           background-color: yellow;
        }
    </style>
</head>
<body>
<ul id="yx">
    <li>单机游戏</li>
    <li id="wl"><a href="#">网络游戏</a></li>
    <li>手机游戏</li>
</ul>
<script>
    var yx = document.getElementById('yx');
    yx.addEventListener('click',function (event) {
        console.log(event.target);
//        target属性-获取绑定当前事件目标元素
        console.log(event.currentTarget);
//        currentTarget属性-获取绑定当前事件目标元素
        console.log(this);
    });
    yx.attachEvent('onclick',function (event) {
//    IE8以下浏览器提供srcElement属性为target目标元素
        var e = event || window.event;
        console.log(e.srcElement);
    });
</script>
</body>

6. Prevent the default behavior

No Use the default, but

<body>
<a href="#">链接</a>
<script>
    var aElement = document.getElementsByName('a');
    /*aElement.addEventListener('click',function(event){
        event.preventDefault();// 阻止默认行为
    });*/
    
    aElement.onclick = function (event) {
        event.preventDefault();
        return false;

    }
    aElement.attachEvent('onclick',function (event) {
        var e = event || window.event;
        e.returnValue = false;
    })
</script>
</body>

7. Get the mouse

pageX and pageY represent the visible area

screenX relative to the page
clientX and clientY and screenY represent

<body>
<script>
    var html = document.documentElement;
    html.addEventListener('click',function(event){
        console.log(event.pageX, event.pageY);
        // 鼠标坐标值相对于当前HTML页面
        console.log(event.clientX, event.clientY);
        // 鼠标坐标值相对于当前可视区域
        console.log(event.screenX, event.screenY);
        // 鼠标坐标值相对于当前屏幕的

        // 鼠标坐标值只能获取,不能设置
    });

</script>
</body>

8 of the current screen, event flow

<style>
        #q1 {
            width: 200px;
            height: 200px;
            background-color: red;
            padding: 50px;
        }
        #q2 {
            width: 100px;
            height: 100px;
            background-color: yellow;
            padding: 50px;
        }
        #q3 {
            width: 100px;
            height: 100px;
            background-color: blue;
        }
    </style>
</head>
<body>
<div id="q1">
    <div id="q2">
        <div id="q3"></div>
    </div>
</div>
<script>
    var q1 = document.getElementById('q1');
    q1.addEventListener('click',function(){
        console.log('这是d1... ...');
    }, false);
    var q2 = document.getElementById('q2');
    q2.addEventListener('click',function(){
        console.log('这是d2... ...');
    }, false);
    var q3 = document.getElementById('q3');
    q3.addEventListener('click',function(event){
        console.log('这是q3... ...');
        event.stopPropagation();
    }, false);
</script>
</body>

9, and event delegation

A large amount of HTML Elements registering the same event and event handle logic security will be the same, which will cause page speed to decrease. If the event flow does not allow these HTML elements to register events with the parent element

<body>
<div id="qh">
    <button id="qyc1">按钮</button>
    <button id="qyc2">按钮</button>
    <button id="qyc3">按钮</button>
</div>
<script>
    var qyc1 = document.getElementById('qyc1');
    qyc1.addEventListener('click',function(){
        console.log('这是个按钮');
    });
    var qyc2 = document.getElementById('qyc2');
    qyc2.addEventListener('click',function(){
        console.log('这是个按钮');
    });
    var qyc3 = document.getElementById('qyc3');
    qyc3.addEventListener('click',function(){
        console.log('这是个按钮');
    });
    var qh = document.getElementById('qh');
//    不把事件绑定给指定元素,绑定给共同父级和祖先元素
    qh.addEventListener('click',function (event) {
        var target = event.target;//触发事件目标元素
        if(targe.nodeName === 'BUTTON') {
           console.log('这是个按钮');
        }
    })
</script>
</body>
Related recommendations:

JS DOM event model analysis

Understanding DOM events in javascript_javascript skills

The above is the detailed content of Event analysis of DOM in javascript (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn