DOM and BOM summary and event content

DOM and BOM Summary

BOM (bowser object model) browser object model

  • window window object (global variables and functions belong to window (global object))

  • location address bar object (get the content of the address bar and use the address bar to jump to the page)

Properties: hash, search, host, hostname, pathname, port, protocol, origin, href

Methods: assign, replace

  • history history object

Attributes: state, length

Methods: forward, back, go, pushState, replaceState

  • screen screen object

Properties: width, height, availWidth, availHeight...

  • navigator navigation object

Attribute: userAgent

  • frames window (window)

DOM (document object model) document object model

  • document document object (the entire html document)

  • element element object (all tags)

  • attribute attribute object (attributes in all tags)

  • text text object (displayed text)

Knowledge points in dom:

  • Empty text (newlines, tabs, spaces...) is also a text node

  • If the attribute is its own attribute, it can be directly . out (input.value, img.src, a.href...) If not, it cannot be clicked out.

  • dom will operate the corresponding HTML content, when your html content, when your html content changes, then the corresponding page will be re-rendered. Will cause a lot of repaints and reflows. (Subsequent dom operations are discarded (efficiency))

Redraw and reflow (reflow must redraw)

  • Redrawing corresponds to an element operation (does not change its width and height and corresponding position but changes other styles)

  • Reflow the corresponding element operation (change all the content of the corresponding element, the width and height and the corresponding position will change)

event

Overview:

Events are an asynchronous mechanism. It is equivalent to an executor execution---observer---processing function execution This process is called an event

composition of events

  • event name (built-in)

  • execution object (element object)

  • Handler function (custom function)

  • Observer (time engine for js)

example

I went to the convenience store to buy Baohuazi, and the boss told me that it was out of stock. I told the boss to wait for the stock to notify me. The boss notified me when the goods arrived, and I went to buy them.

analyze

Event Name ---- Buy Huazi

executor ---- me

Observer --- Boss

Handling --- Bought Huazi

Example

<button>click</button>
<script>
button.onclick = function(){
    console.log('clicked')
}
</script>

event name click (built-in)

Execute object button (element object)

Processing function Subsequent functions (custom functions)

Observer (js engine event thread (engine))

An event written in js has its observers all event engines. What we need to pay attention to is the first three contents (event name, execution object, handler function)

How to write the declaration of the event

inline mode (inside a tag)

<!--inline mode is onclick Set the corresponding code in writing-->
<button onclick="alert('hello')">I point</button>
<button onclick="fn(1)">click me 1</button>
<!-- Note: Calling a function in inline mode needs to be called manually, and the function name needs to be deep'()'bring -->
<script>
        function fn(arg){
            alert('I am function execution'+arg)
            console.log(this);//window
        }
</script>

Script mode (commonly used in the script tag)

<!--script mode-->
<button>script mode</button>
<script>
        //Writing in script mode Event name Execution object Handler function
        var btn = document.getElementsByTagName('button')[2]
        //Execution object.on+event name = handler function
        btn.onclick = function(){
            console.log('hello');
        }
        function handler(){
            console.log('The handler function is executed');
        }
        //Calling a function in script mode does not need to be called manually, just assign the corresponding function name to the corresponding click event to call, as shown below:
        btn.onclick = handler
        //This in the function call in inline mode points to the window corresponding to the script mode this in the current caller
</script>
The difference between inline mode and script mode
  • Calling a function in inline mode needs to be called manually, and the processing function of the corresponding script mode is automatically called

  • This in the function call in inline mode points to the window corresponding to the script mode this in the current caller

Event name classification

Mouse events (mouse triggered by the mouse)

  • click click event

  • dblclick double click event

  • mousedown pressed

  • mouseup pop up

  • mouseenter move in

  • mouseleave out

  • mouseover move in

  • mouseout out

  • mousemove move

  • contextmenu right click

Precautions

  • The execution order of click and corresponding mousedown and mouseup (mousedown -- mouseup -- click)

  • The difference between mouseenter(mouseleave) and mouseover(mouseout) (mouseenter child elements will not trigger mouseover child elements will trigger)

<style type="text/css">
        div{
            background-color: red;
            width: 100px;
            height: 100px;
        }
</style>
<div>I am a div
        <div style="background-color:yellow;height:50px;width:50px;float:left"></div>
    </div>
    <script>
        //get div
        var div = document.querySelectorAll('div')[0]
        //script mode
        div.onclick = function(){
            console.log('click event executed');
        }
        //Double click event must trigger click
        div.ondblclick = function(){
            console.log('Double click event executed');
        }
        //Mouse down and up Execution sequence Press -- up -- click
        div.onmousedown = function(){
            console.log('mouse down')
        }
        div.onmouseup = function(){
            console.log('mouse up');
        }
        //mouse in and out
        //enter and leave will not fire when entering child elements
        div.onmouseenter = function(){
            console.log('mouse over');
        }
        div.onmouseleave = function(){
            console.log('mouse out');
        }
        //over and out entering child elements will also trigger
        div.onmouseover = function(){
            console.log('mouse over moved in');
        }
        div.onmouseout = function(){
            console.log('mouse out removed');
        }
        //mouse movement
        div.onmousemove = function(){
            console.log('mouse moved');
        }
        //Right mouse click (click event will not fire)
        div.oncontextmenu = function(){
            console.log('right mouse click');
        }
    </script>

Keyboard events (keys triggered by the keyboard)

keydown

keyup

keypress string (other than function keys)

<input type="text" />
<script>
    //get input box
    var input = document.querySelector('input')
    //keyboard related events
    input.onkeydown = function(){
        console.log('keyboard pressed');
    }
    //In the input Chinese input state, the pop-up will appear twice
    input.onkeyup = function(){
        console.log('keyboard pops up');
    }
    //Character key press (except function keys)
    input.onkeypress = function(){
        console.log('character key press');
    }
    window.onkeypress = function(){
        console.log('exist window triggered on keypress event');
    }
</script>

Precautions

  • Execution order keydown -- keypress -- keyup

  • keypress will definitely trigger keydown

HTML events (some events that come with HTML (only available for specialized HTML))

window event

  • Load event (load)

  • Unload event (unload)

  • Close the window event (onclose)

  • Event called before printing (onbeforeprint)

  • Event called before unloading (onbeforeunload)

  • The event that the scroll bar changes (onscroll)

<style type="text/css">
    div{
        height: 100px;
        width: 100px;
        overflow: scroll;
    }
</style>
<body style="height:3000px">
    <div>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
    </div>
    <form action="">
        <input type="text" />
        <button type="submit">submit</button>
        <button type="reset">reset</button>
    </form>
    <script>
        //load event
        window.onload = function(){
            console.log('hello');
        }
        //unload event (refresh)
        window.onunload =function(){
            console.log('uninstall');
        }
        //Close window event (clear related cache and corresponding resource operation)
        window.onclose = function(){
            console.log('closure');
        }
        //Call before printing Before calling the print method, you can change the printed content and continue printing
        window.onbeforeprint = function(){
            console.log('printed');
        }
        //Called before unloading to recycle some content
        window.onbeforeunload = function(){
            console.log('before uninstall');
        }
        //scroll bar scroll
        window.onscroll = function(){
            console.log('The position of the scroll bar changes');
        }
        //Other uses of load events
        var image = new Image()//build a picture object
        image.onload = function(){//If the image is loaded
            image.src = 'The map's address'//Set the corresponding src address for the image
        }
        //Other uses of onscroll
        document.querySelector('div').onscroll = function(){
            console.log('div the scroll bar scrolled');
        }
    </script>
</body>

form events

  • submit form submit event

  • reset form reset event

  • select content is selected (only for input boxes and text fields)

  • The value of the change form changes

  • input Input in the form tag that can be entered

  • blur loses focus

  • focus gets the focus

<style type="text/css">
    div{
        height: 100px;
        width: 100px;
        overflow: scroll;
    }
</style>
<body style="height:3000px">
    <div>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
        <p>1111111</p>
    </div>
    <form action="">
        <input type="text" />
        <button type="submit">submit</button>
        <button type="reset">reset</button>
    </form>
    <script>
        //Form related events
        //Events added to the entire form
        document.forms[0].onsubmit = function(){
            console.log('submitted');
        }
        document.forms[0].onreset = function(){
            console.log('reset');
        }
        //change value value changes and loses focus
        document.querySelector('input').onchange = function(){
            console.log('value changed');
        }
        //input is called when the corresponding value is entered
        document.querySelector('input').oninput = function(){
            console.log('input value');
        }
        //select select the content inside
        document.querySelector('input').onselect = function(){
            console.log('selected value');
        }
        //lose focus
        document.querySelector('input').onblur = function(){
            console.log('lost focus');
        }
        //focus
        document.querySelector('input').onfocus = function(){
            console.log('got focus');
        }
    </script>
</body>

Correlative focus and defocus methods

focus method

How to blur out of focus

//element also has focus() blur()
document.querySelector('input').focus()
setTimeout(function(){
    document.querySelector('input').blur()
},3000)

event event source object

Overview

Event is called the event source object, which is a global built-in object (belonging to window), which contains some related properties about event execution.

Arguments in the handler

The handler function is also a function, and the function has an argument property. arguments is a pseudo-array. Then you can know that the corresponding processing function also has arguments

var btn = document.querySelector('button')
btn.onclick = function(){
    //After the click event is triggered, there is a corresponding pointerEvent object in the corresponding arguments.
    console.log('arguments',arguments);
    console.log(`arguments[0]`,arguments[0]);
    //This object actually exists in the first place in the arguments, which is mainly based on attributes, so what does this object represent?
    //This parameter is actually some content of the corresponding event, called the event source object event
}
window.onkeydown = function(){
    console.log('arguments',arguments);
    //keyboardEvent The event source object of the keyboard
    console.log(`arguments[0]`,arguments[0]);
}

From the above code, it can be obtained that the handler function of the corresponding event execution will pass a parameter, and the type of this parameter is an event. There is only one element in the arguments array of this handler function.

Therefore, we can abbreviate as

//The e in this place is generally written as e or event
btn.onclick = function(e){
    //The e in this place represents the first parameter, which is the corresponding event object. This event has compatibility problems in this.
    //Compatible spelling
    e = e || window.event
    //This e represents the first parameter, then he is our corresponding event object
    console.log(`e`,e);
}

Common properties of event

Properties related to mouse coordinates

screenX represents the x distance of the mouse from the screen

screenY represents the y distance of the mouse from the screen

pageX represents the x distance of the current mouse from the page (including the rolled up part)

pageY represents the y distance of the current mouse from the page (including the rolled up part)

clientX represents the x distance of the mouse from the visible area of ​​the page

clientY represents the y distance of the mouse from the visible area of ​​the page

offsetX represents the x distance that the mouse is offset from the parent element

offsetY represents the y distance that the mouse is offset from the parent element

 

Button helper related properties

  • ctrlKey Whether the ctrl key is pressed

  • shiftKey Whether the shift key is pressed

  • altKey Whether the alt key is pressed

//Auxiliary key property returns a boolean value
console.log(e.ctrlKey);//Whether to long press ctrl
console.log(e.altKey);//Whether to long press alt
console.log(e.shiftKey);//Whether to long press shift

Mouse related properties

  • button which key is pressed

//what key was pressed three values ​​0 1 2
console.log(e.button);Left button 0 Middle wheel 1 Right button 2

Events and related trigger properties

  • type the current property type

//Event Type Returns the event name
console.log(e.type);//click
  • target represents the trigger object of the current event

//trigger element
console.log(e.target);
//add event element
console.log(e.currentTarget);

keyboard related properties

key character representing the currently pressed key (case sensitive)

keyCode (in keydown, it is case-insensitive, all uppercase ascii codes)

code (key + uppercase characters)

charCode (only works in keypress, he is case-sensitive and returns the corresponding ascii code)

window.onkeypress = function(){
    console.log(e.code);//Which is the current button press key and returns a key+capital letter
    console.log(e.keyCode);//The uppercase ascii code of the currently pressed key
    console.log(e.charCode);//The ascii code of the current character in keypress
    console.log(e.key);//Indicates the currently pressed key
}

Event delegation mechanism (event proxy)

Overview: Delegate the corresponding event to the corresponding parent element, and then obtain the actual trigger element to operate through the corresponding e.target.

Example

//How to write event delegation
//Get the parent element to which the event needs to be added
var ul = document.querySelector('ul')
//add event to ul
//Add event to parent element
//Internally judge the trigger element e.target
//corresponding action
ul.onclick = function(){
    e = e || window.event
    //Determine whether the current departure element is li
    if(e.target.tagName == 'LI'){
        //exclusive thought
        //Clear all li class es
        for (var item of this.children){
            item.className = ''
        }
        e.target.className = 'active'
    }
}

Application scenarios of event delegation

When there are multiple child elements in a parent element to add the same event

Tags: html Front-end Javascript

Posted by sillyman on Sun, 16 Oct 2022 10:47:02 +1030