DOM learning notes

DOM (document object model), a standard programming interface recommended by W3C organization to deal with extensible markup language (HTML/XML).
The content, structure and style of web pages can be changed through DOM interface
For JavaScript, in order to enable JavaScript to operate HTML,JavaScript has its own dom programming interface.
For HTML,dom makes html form a dom tree, including documents, elements and nodes.
The DOM element we obtained is an object, so it becomes the document object model
Create, add, delete, modify, query, attribute operation and event operation of elements.

establish

  1. document.write
  2. innerHTML
  3. createElement

increase

  1. appendChild
  2. insertBefore

Delete

  1. removeChild

change

It mainly modifies the element attributes of dom, the contents and attributes of dom elements, and the values of forms.

  1. Modify element attribute: src href title
  2. Modify common element content: innerHTML innerText
  3. Modify form element: value type disabled
  4. Modify element style: style className

check

It mainly gets the elements of the query DOM

  1. API method provided by DOM: getElementById getElementByTagName old usage
  2. A new method provided by H5: querySelector querySelectorAll
  3. Using node operations to obtain elements: parent node, child and sibling

Attribute operation

It is mainly aimed at custom attributes.

  1. setAttribute: sets the attribute value of dom
  2. getAttribute: get the attribute value of dom
  3. removeAttribute remove attribute

Event operation

Register the event for the element and take the event source Event type = event handler

Mouse eventTrigger condition
onclickClick the left mouse button to trigger
onmouseoverMouse over trigger
onmouseoutMouse departure trigger
onfousGet mouse focus trigger
onblurLoss of mouse focus trigger
onmousemoveMouse movement trigger
onmouseupMouse bounce trigger
onmousedownMouse press trigger

Registration event

  1. Traditional way: uniqueness
<button onclick="alert('HelloWorld')"></button>
btn.onclick = function(){
}
  1. Method monitoring registration method
eventTarget.addEventListener(type,listener[, useCapture])
// Type: event type string, such as click mouseover
// listener: event handling function, which will be called when an event occurs
// useCapture: optional parameter. It is a Boolean value. It is false by default.

Ie before IE9 does not support this method. attachEvent() can be used instead
Features: multiple listeners can be registered for the same element and event

Example:

<body>
    <button>Traditional registration event</button>
    <button>Method listens for registration events</button>
    <script>
        var btns = document.querySelectorAll('button');
       // Register events in traditional way
        btns[0].onclick = function () {
            alert('Hello');
        }
        // Event listener registration event
        btns[1].addEventListener('click', function () {
            alert('World');
        })
    </script>
</body>

Delete event

<body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <script>
        var divs = document.querySelectorAll('div');
        divs[0].onclick = function(){
            alert(11);
            //1. Delete events in traditional way
            divs[0].onclick = null;
        }

        divs[1].addEventListener('click',fn); //There is no need to add parentheses to fn inside
        function fn(){
            alert(22);
            divs[1].removeEventListener('click',fn);
        }

        divs[2].attachEvent('onclick',fn1);
        function fn1() {
            alert(33);
            divs[2].detachEvent('onclick',fn1);
        }
    </script>
</body>

DOM event flow

Event flow describes the order in which events are received from the page.
When an event occurs, it will propagate between element nodes in a specific order. This propagation process is DOM event flow.

  1. Capture phase

  2. Current target stage

  3. bubbling phase

  4. Only one stage of capture or bubbling can be executed in JS code.

  5. onclick and attachEvent can only get the bubbling phase

  6. If the third parameter of addEventListener(type,listener{,useCapture}) is true, it means to call the event handler in the event capture phase; If false (default is false if you don't write), it means that the event handler is called in the event bubbling phase.

  7. In actual development, we rarely use event capture, and we pay more attention to event bubbling

  8. Onblur, onfocus, onmousenter, onmouselive

Event object

<body>
    <div>123</div>
    <script>
        //Event object
        var div = document.querySelector('div');
        div.onclick = function(event){
            console.log(event);
        }
        //1. event is an event object written into the parentheses of our listening function
        //2. The event object will exist only when there is an event. It is automatically created by the system and does not need us to pass parameters.
        //3. The event object is the collection of a series of relevant data of our events. For example, the mouse click contains the relevant information of the mouse and the mouse coordinates. If it is a keyboard event, it contains the information of the keyboard event, such as judging which button the user pressed
        //4. Name the event object event evt e
        //5. The event object also has compatibility problems ie678 through window event
    </script>
</body>

Common event object properties and methods

<body>
    <div>
        abc
    </div>
    <ul>
        <li>abc</li>
        <li>abc</li>
        <li>abc</li>
    </ul>
    <script>
        //Properties and methods of common event objects
        //1. e.target returns the object (element) that triggered the event
        var div = document.querySelector('div');
        div.addEventListener('click',function(e){
            console.log(e.target);  //e.target returns the object (element) that triggered the event. this returns the object (element) that bound the event
            console.log(this);
        });
        var ul =document.querySelector('ul');
        ul.addEventListener('click',function(e){
            console.log(this); //this points to the object that binds the event
            console.log(e.target);  //e.target points to the object we clicked on 
        }) 
    </script>
</body>

Event object blocks default behavior

<body>
    <div>123</div>
    <a href="http://www.bilibili.com">bilibili</a>
    <form action="http://www.bilibili.com">
        <input type="submit" value="Submit" name="sub">
    </form>
    <script>
        //Properties and methods of common event objects
        //1. Return event 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);
        }

        //2. Block the default behavior (event) so that the link does not jump or the submit button does not submit
        var a = document.querySelector('a');
        a.addEventListener('click',function(e){
            e.preventDefault();  //dom standard writing
            //3. Traditional registration methods
            a.onclick = function(e){
                //Normal browser
                e.preventDefault();  //method
                //Lower browser ie678 returnvalue attribute
                e.returnValue;
                //We can also use return false to prevent the default behavior. There is no compatibility problem, but it is limited to the traditional registration method
                return false;
            }
        });
    </script>
</body>

Prevent event bubbling

<body>
   <div class="father">
       <div class="son">son Son</div>
   </div>
   <script>
       //Properties and methods of common event objects
       //Stop bubbling dom recommendation stopPropagation()
       var son = document.querySelector('.son');
       son.addEventListener('click', function (e) {
           alert('son');
           if (e && e.stopPropagation) {
               e.stopPropagation();  //Stop stop propagation
           } else {
               window.event.cancelBubble = true;
           }
       }, false);
       var father = document.querySelector('.father');
       father.addEventListener('click', function () {
           alert('father');
       }, false);
       document.addEventListener('click', function () {
           alert('document');
       })
   </script>
</body>

Event delegation

Event delegation is also called event proxy, which is called event delegation in jQuery.
Principle of event delegation:
Instead of each child node stalking the event listener alone, the event listener is set on its parent node, and then the bubble principle is used to influence the setting of each child node.

<body>
    <ul>
        <li>0</li>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <script>
        //Event delegation
        var ul = document.querySelector('ul');
        var lis = document.querySelectorAll('li');
        ul.addEventListener('click', function (e) {
            // alert('Hello World!');

            for (var i = 0; i < lis.length; i++) {
                lis[i].style.backgroundColor = 'white';
            }
            e.target.style.backgroundColor = 'blue';
        });
    </script>
</body>

Common mouse events


Get current mouse coordinates

<body>
    <script>
        //Mouse event object
        document.addEventListener('click', function (e) {
            //clientx mouse xy in the visible area
            console.log('---------------');
            console.log(e.clientX);
            console.log(e.clientY);
            //pageX pageY
            console.log(e.pageX);
            console.log(e.pageY);
            //screenX screenY
        })
    </script>
</body>

The picture moves with the mouse

<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/bing.png" alt="">
    <script>
        var pic = document.querySelector('img');
        document.addEventListener('mousemove', function (e) {
            //1.
            console.log('Locaton: ' + e.pageX + ' ' + e.pageY);
            pic.style.left = e.pageX + 'px';
            pic.style.top = e.pageY + 'px';
        })
    </script>
</body>

Common keyboard events




Reference: pink teacher tutorial

Keywords: Javascript Front-end html

Added by xplosiongames on Wed, 26 Jan 2022 19:46:46 +0200