This is the 29th day of my participation in the August Wenwen Challenge.More challenges in August


Document Object Model supplement

01. Operation elements

(1) Another way to get elements

  • Get elements using node hierarchies

    Everything on a page is a node

  • Basic attributes:

    • NodeType, nodeName, nodeValue: nodeType, nodeName, and nodeValue

      Element node: nodeType is 1

      Attribute node: nodeType is 2

      Text node: nodeType is 3 (text node includes text, space, line feed, etc.)

  • Parent node:

    • parentNode

      Returns the nearest parent node to the element, or null if there is none

  • Child node:

    • childNodes

      Get all child nodes, including element nodes, text nodes

    • children

      Gets all child element nodes

    • firstChildandlastChild

      Gets the first (and last) child node, either a text node or an element node

    • firstElementChildandlastElementChild

      Get the first (last) child element node, compatibility issue, IE9 support above

    • parentNode.children[0] parentNode.children[parentNode.children.length - 1]

      Returns the first (last) child element, no compatibility issues

      Parentnode. children returns a pseudo-array,

      ParentNode. Children. Length – 1: the last child said

  • Sibling nodes:

    • nextSiblingandpreviousSibling

      Gets the next (previous) sibling node, containing element node, text node, and so on

    • nextElementSiblingandpreviousElementSibling

      Get the next (previous) sibling element node, compatibility issues, IE9 support above

    • Resolve compatibility issues: Encapsulate a function yourself

      The first method is implemented by determining the nodeType value


(2) Dynamically operate element nodes

  • Creating element nodes

    • document.createElement(" ");

    Dynamically create element nodes

  • Add element node

    • parentNode.appendChild("child");

    Appends a child element child to the end of the parent element parentNode

    • Parentnode. insertBefore("child", "specified element ");

    In the parent element parentNode, appends the child element child to the other specified child elements

  • Delete element node

    • parentNode.removeChild("child");
  • Copy element node

    • node.cloneNode();

    Returns a copy of the node on which the method was called


    If the parentheses are empty, or false, it is a shallow copy, copying only the tags and not the contents inside

    If the parentheses are true, it is a deep copy, copying both the tag and the contents inside


(3) The differences between the three methods of dynamically creating elements

Document.write, element.innerhtml, document.createElement()

  • About the document. The write () :

    • document.writeIs a content stream that writes content directly to a page,
    • Execute if it is after the document flow has finished executing document.write, will cause the page content to be completely redrawn
  • About element. InnerHTML:

    • Creating multiple elements is efficient, but the structure is slightly more complex
    • But adding elements to the page by concatenating strings is inefficient (immutability of strings)
    • Therefore, we can use the method of ** arraypush()** Add elements for maximum efficiency
  • About the document. The createElement method () :

    • Creating multiple elements is less efficient, but the structure is clearer
    • throughAppenChild ()It is efficient to append the child element directly to the end of the parent element

02. [Events] about page elements

(1) Basic concepts

  • Basic event composition

    • Three elements of the event:
      • Event source: The object from which the event is fired
      • Event types: How to trigger events, such as click, slide, keyboard input, etc.
      • Event handler: What event completes
    • aboutthis
      • thisPoints to theEvent functionstheThe caller
  • Basic event execution process

//1. First get the event source element
var btn = document.getElementById("btn")
//2. Then bind events (register events)
//3. Finally add the event handler
div.onclick = function(){
    alert("Trigger event")}Copy the code

(2) Two ways in which the element registers the event

  • Traditional Registration

    • usingonInitial events such as:onclick
    • Uniqueness: Only one handler can be set for an event of the same element, and the last one registered overrides the previous one
  • AddEventListener Event listener

    • Grammatical structure:eventTarget.addEventListener(type, listener, useCapture);
      • Registers the specified listener with the eventTarget

      • Type: a string of event types, such as click and Mousemover

      • Listener: An event handler that is called when an event occurs

      • UseCapture: Optional, a Boolean value, false by default

  • Register event

eventTarget.addEventListener("type".function// Bind to the target functiontypeEvent, whose handler isfunction

Copy the code

(3) The way to delete events

  • Delete events in the traditional way

    • eventTarget.onclick = null
  • RemoveEventListener Deletes the event

    • eventTarget.removeListener
    eventTarget.removeListener("type".function) // Remove the target objecttypeEvent, the event bindingfunctionThe processing functionCopy the code

(4) DOM event flow

  • The basic concept

    • Event flow refers to the order in which events are received from the page
      • When events occur, they are propagated in a specific order between element nodes, in a process known as the DOM event stream
  • Summary of stage

    • Capture phase

      • The process of starting from the topmost node of the DOM and propagating down to the target element’s reception

      • In cascading down (sink), if an ancestor is bound to an event of the same type (such as a click), events (click events) are triggered in descending order (from top to bottom) when the target descendant element events are triggered (after a click)

    • Current target stage

    • Bubbling phase

      • The event is received from the target event element and propagated up the hierarchy to the topmost node in the DOM

      • In cascading up (bubbling), if an ancestor element is bound to the same type of event (such as a click event), events (click events) are emitted in the bubbling order (from bottom to top) when the target descendant element events are emitted (after a click)

  • Other considerations

    • onclickEtc.onThe initial event only triggers the bubble phase
      • 【 note 】onblur,onfocus,onmouseenter,onmouseleaveThere is no bubble stage
    • addEventListenerMultiple stages can be triggered
      • useCapture: The parameter value istrue, is the capture phase
      • useCapture: The parameter value isfalse, is the bubbling stage

(5) Event object

  • The basic concept
    • After an event occurs, a series of information data sets related to the event will be stored in an event object

      • eventObject, representingState of eventsFor example, the status of the keyboard keys, the position of the mouse, and the status of the mouse button
    • The event object exists only when there is an event. It is automatically created by the system, that is, it does not need to be passed in

      eventTarget.onclick = function(event){... }Copy the code

      The event object can be named by ourselves, such as Event, EVT, e

    • Compatibility issues with event objects

      • IE6, 7, 8 will only recognizewindow.event

      Compatible with: e = e | | window. The event;

(6) Common properties and methods of event objects

  • Return the object that triggered the event: returns whoever triggered the event, syntax: e.target

  • Returns the object to which the event is bound: returns the object to which the event is bound, syntax: this

  • Return the type of the event that was triggered. The syntax is e.type

  • Blocking default events

    • Higher version: e.preventDefault() :

    • Earlier versions (Internet Explorer 6, 7, and 8) : e.turn Value

    e.onclick = function(e) {
        // Common browser e.preventdefault () method
         e.preventDefault()
        // Lower version Browser IE678 returnValue property
         e.returnValue
        // We can also prevent default behavior by using return false
        // There are no compatibility issues
        return false
    }
    Copy the code
  • Prevents events from bubbling

    • E.toppropagation ()

    • Nonstandard notation: e.cancelbubble = true

      if(e && e.stopPropagation){
          e.stopPropagation()
      }else{
          window.event.cancelBubble = true
      }
      
      Copy the code

(7) Event delegation (agent, delegate)

  • Instead of setting event listeners for each child node individually, you set event listeners on its parent node, delegating events to the parent node

    Because the event bubbles, clicking on the child will bubble up to the parent node, which will also trigger the event, and then you can use e.target to find which child triggered the event (who was clicked)


    What the event delegate does: Manipulates the DOM only once


03. Mouse incident

(1) Basic events

  • Onclick: mouse click event

  • Onfocus: Gets the focus event

  • Onblur: out-of-focus events

  • Onmouseover: mouseover event

    • Passing through a child element also fires an event for the parent element
  • Onmouseenter: mouse over event (does not bubble)

    • Only through the box itself
  • Onmouseout: Mouse away event

    • Passing through a child element also fires an event for the parent element
  • Onmouseleave: Mouse away event (does not bubble)

    • Only through the box itself

  • Blocking link hops

    <a href="javascript:void(0);">Click Not to jump</a>
    
    <a href="javascript:;">Click Not to jump</a>
    
    Copy the code
  • Disable the right mouse menu: ContextMenu

    e.addEventListener("contextmenu".function(e) {
        e.preventDefault()
    })
    
    Copy the code
  • Disable mouse selection: selectStart

    e.addEventListener("selectstart".function(e) {
        e.preventDefault()
    })
    
    Copy the code

(2) Mouse event object

  • The mouse coordinates

    • e.clientXande.clientY

    Gets the coordinates of the mouse relative to the client’s visible window area

    • e.pageXande.pageY———— (main)

    Gets the coordinates of the mouse relative to the page document

    • e.screenXande.screenY

    Gets the coordinates of the mouse relative to the computer screen

  • The mouse moves

    • mousemove

    Whenever the mouse moves, the event is triggered

    document.addEventListener('mousemove'.function(e) {
       console.log("X coordinates." + e.pageX + "Y," + e.pageY)
    })
    
    Copy the code

04. Keyboard events

(1) Basic events

  • Keyup: triggered when the key is lifted, but only once when the keyboard is released

  • Keydown: Triggered when a key is pressed, the function key can be identified

    • The press will not release the trigger
  • Keypress: This function is triggered when a key is pressed. Function keys, such as CTRL, Shift, and left and right arrows, cannot be identified

    The response sequence of keyboard events is keyDown → keyPress → keyUp

    【 Attention 】 The differences and application scenarios of the three

(2) Keyboard event object

  • E. keycode: Returns the ASCII code value of the corresponding key

    You can tell which key the user pressed

    • Keyup and keyDown are case insensitive and display keys in uppercase state

    • Keypress is case sensitive


I front-end side dish chicken, if there is wrong, please forgive