The target

  • Understand the browser object model
  • Analyze the browser’s Event Model

The main points of

What is the Browser object Model

BOM: The Browser Object Model provides a content-independent Object structure that slides with the Browser window.

Common API

  1. The Window object

The Window object is the core of the browser object model and acts as both an interface and a global object

Event

  • alert()
  • confirm()
  • prompt()
  • open()
  • onerror()
  • setTimeout()
  • setInterval()
  • .

The window position

  • screenLeft
  • screenTop
  • screenX
  • screenY
  • moveBy(x,y)
  • moveTo(x,y)
  • .

The window size

  • innerWidth
  • innerHeight
  • outerWidth
  • outerHeight
  • resizeTo(width, height)
  • resizeBy(width, height)
  • .
  1. Location object

Provides information about the loaded document in the current window and some navigation capabilities. It is both a window object property and a Document object property

The main properties

  • hash
  • host
  • hostname
  • href
  • pathname
  • port
  • protocol
  • search
  • .
  1. Navigation object

The Navigator represents the status and identity of the user agent, allowing the script to query it and register itself for some activities

Common properties

  • appName
  • appVersion
  • bluetooth
  • clipboard
  • connection
  • keyboard
  • language
  • userAgent
  • .
  1. The History object

The history object holds a history of the user’s Internet access from the moment the window was opened. The history object is represented by the window’s browsing history in the form of documents and a list of document states

Common properties

  • go()
  • back()
  • forword()
  • length

Browser event capture, bubbling

The process in the browser event model is divided into three phases: capture phase, target phase, and bubble phase

  1. The third parameter

Note that the third argument to addEventListener, if true, is executed in the capture phase. If false, it is in the bubbling phase

// html
<body>
    <div id="yeye" class="flex-center">grandpa<p id="baba" class="flex-center">dad<span id='erzi' class="flex-center">son<a href="https://www.baidu.com" id="a-baidu">Click the test</a>
            </span>
        </p>
    </div>
  </body>
Copy the code
// js
const yeye = document.getElementById("yeye");
const baba = document.getElementById("baba");
const erzi = document.getElementById("erzi");

window.addEventListener("click".function (e) {
    // e.target.nodeName refers to the currently clicked element. E.currenttarge. nodeName binds the element that listens for the event
    console.log("Window capture", e.target.nodeName, e.currentTarget.nodeName);
}, true);

yeye.addEventListener("click".function (e) {
    console.log("Yeye capture", e.target.nodeName, e.currentTarget.nodeName);
}, true);

baba.addEventListener("click".function (e) {
    console.log("Baba capture", e.target.nodeName, e.currentTarget.nodeName);
}, true);

erzi.addEventListener("click".function (e) {
    console.log("Capture erzi", e.target.nodeName, e.currentTarget.nodeName);
}, true);

window.addEventListener("click".function (e) {
    console.log("The window" bubble., e.target.nodeName, e.currentTarget.nodeName);
}, false);

yeye.addEventListener("click".function (e) {
    console.log("Yeye" bubble., e.target.nodeName, e.currentTarget.nodeName);
}, false);

baba.addEventListener("click".function (e) {
    console.log("Baba" bubble., e.target.nodeName, e.currentTarget.nodeName);
}, false);

erzi.addEventListener("click".function (e) {
    console.log(Erzi "bubble", e.target.nodeName, e.currentTarget.nodeName);
}, false);
Copy the code

As a result ❓

  1. Preventing an event from spreading

If there are multiple event listeners of the same type of event bound to the same element, when events of that type are fired, they are executed in the order in which they were added. If one monitor function performs the event stopImmediatePropagation () method, which is the rest of the current element to monitor function will not be executed.

e.stopPropagation()

baba.addEventListener("click".function (e) {
    // baba prevents event propagation -> downward capture
    e.stopPropagation()
    console.log("Baba capture", e.target.nodeName, e.currentTarget.nodeName);
}, true);
Copy the code

  1. Blocking default behavior

This prevents the default behavior of the event from occurring. Default behavior means clicking the A TAB to jump to another page, dragging an image to the browser opens automatically, clicking the submit button on a form submits a form, and so on, because sometimes we don’t want these things to happen, so we need to prevent default behavior.

e.preventDefault()

document.getElementById('a-baidu').addEventListener("click".function (e) {
    // prevents the default jump behavior of the A tag
    e.preventDefault()
});
Copy the code
  1. compatibility

AttachEvent — Compatible with IE7 and IE8; The third parameter is not supported to control which phase occurs, the default is to bind addEventListener in bubbling phase — compatible with: Firefox, Chrome, IE, Safari, Opera;

Handwriting encapsulates compatibility 🔻

class XuSir_BomEvent {
    constructor(element) {
        // Pass it to me
        this.element = element;
    }

    /** * bind listener *@param {*} Type Indicates the event type *@param {*} Handler callback function */
    addEvent(type, handler) {
        if (this.element.addEventListener) {
            // Event type, function to execute, whether to capture
            this.element.addEventListener(type, handler, false);
        } else if (this.element.attachEvent) {
            // Compatible with IE9 and later versions
            this.element.attachEvent('on' + type, function () {
                handler.call(element);
            });
        } else {
            this.element['on'+ type] = handler; }}/** * remove listener *@param {*} Type Indicates the event type *@param {*} Handler callback function */
    removeEvent(type, handler) {
        if (this.element.removeEnentListener) {
            this.element.removeEnentListener(type, handler, false);
        } else if (element.datachEvent) {
            this.element.detachEvent('on' + type, handler);
        } else {
            this.element['on' + type] = null; }}}// Prevent events (mainly event bubbling, since IE does not support event capture)
function stopPropagation(ev) {
    if (ev.stopPropagation) {
        ev.stopPropagation(); / / the w3c standards
    } else {
        ev.cancelBubble = true; // IE}}// Cancel the default behavior of the event
function preventDefault(event) {
    if (event.preventDefault) {
        event.preventDefault(); / / the w3c standards
    } else {
        event.returnValue = false; // IE}}Copy the code

Use method: old driver all know 💯

Event delegation

  • 🔴 it also has a name called event proxy, JavaScript advanced programming: event delegate is the use of event bubble, only a specified event handler, you can manage a certain type of all events.
  • 🟠 Event delegation is implemented using the bubbling principle of events. What is the bubbling of events? The event starts at the deepest node and then propagates the event up. For example, there is a node tree on the page, div>ul>li>a; For example, if we add a click event to the innermost DIV, the event will be executed layer by layer in the order of A > Li >ul>div. There is such a mechanism that if we add a click event to the outermost div, ul, Li, and A will all bubble up to the outermost div. So they all fire, and this is called event delegate, and they delegate their parent to execute the event.
  • 🔵 example
<ul id="ul">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
</ul>
Copy the code
/ / way
// Disadvantages ❓ adds a listener for each li element, poor performance
<script type="text/javascript">
const liList = document.getElementsByTagName("li");
for(let i = 0; i<liList.length; i++){
    liList[i].addEventListener('click'.function(e){
        alert(` content for${e.target.innerHTML}, the index for${i}`); }) } </script>Copy the code
2 / / way
<script type="text/javascript">
const ul = document.querySelector("ul");
ul.addEventListener('click'.function (e) {
    consttarget = e.target;if (target.tagName.toLowerCase() === "li") {const liList = this.querySelectorAll("li");
        // Get index method 1
    // const index = Array.prototype.indexOf.call(liList, target);
        // Approach 2 -- more in line with modern browser processing
        const realLiList = Array.from(liList)
        constThe index = realLiList. IndexOf (target) alert (` content for${target.innerHTML}, the index for${index}`); } }) </script>Copy the code

Error correction is welcome, children’s ❤