[JavaScript] Introduction to BOM Basics

preface

BOM technology is widely used in the Web. It mainly defines the operation of client browsers. BOM has not been standardized, but major browsers support BOM. Among them, old IE has many compatibility problems with BOM.

BOM definition

BOM (Browser Object Model) the Browser Object Model is used to access and manipulate the browser window, so that JS can interact with the browser and perform operations that are not directly related to the page content.

Window object

The browser window object replaces the Global in ES in the browser and acts as the Global scope. It is the root object of BOM. Other objects are the properties of window. Its properties and methods can be called directly without window.

Window object properties

Window object method

Event object

Browser Event object. After any Event is triggered, the interpreter will generate an Event object to record the relevant information of the trigger object.

Trigger event

  1. Mouse event
  • onclick mouse click
  • Ondbllick mouse double click
  • onmouseover mouse in
  • onmouseout mouse out
  • onmousemove mouse movement
  • onmousedown mouse down
  • onmouseup mouse release
  • oncontextmenu right click menu
  1. Keyboard events
  • onkeydown trigger key
  • onkeyup release key
  • onkeypress hold key
  1. Status event
  • onfocus get focus
  • onblur lost focus
  • oninput form input
  • onsubmit form submission
  • onchange state change

Binding event

// 1. Defining event related attributes of elements in HTML violates the principle of "separating content from behavior" and uses them as little as possible.
<element on Event name="JS operation"></element>

// 2. Assign values to the event related attributes of the element in JS to realize "separation of content and behavior", but the element can only bind one listening function.
element.onclick = function () {
    JS operation;
}

// 3. Advanced event processing method, which can bind multiple listening functions for an element. It is necessary to pay attention to the compatibility between old IE and mainstream browsers. It can be written in three ways.

// 3.1 mainstream browser syntax
element.addEventListener("Event name", callback);

// 3.2 old IE browser syntax
element.attachEvent("on Event name", callback);

// 3.3 browser compatible syntax
if (element.addEventListener) {
    element.addEventListener("Event name", callback);
} else {
    element.attachEvent("on Event name", callback);
}

Event cycle

The JS event model is divided into three stages, covering the process from the occurrence of an event to the completion of the execution of all event handling functions.

  • The first stage: event capture, event objects propagate down the DOM tree.
  • The second stage: target triggering, and the target element executes the event listening function.
  • The third stage: the event bubbles and the event object propagates upward along the DOM tree.
  • [note] there is no "event capture" stage in IE event model.

Get event object

  • Mainstream browsers: automatically passed in as the first formal parameter of the event handler.
  • Old IE browser: event.
  • Compatible syntax: e = e | event;

Event object application

  1. Get mouse position
  • e.screenX/Y; mouse relative screen coordinates.
  • e.clientX/Y; coordinates of the mouse relative to the document display area.
  • e.pageX/Y; coordinates of the mouse relative to the web page.
  1. Stop bubbling
// Mainstream browser
e.stopPropagation();
// Old IE browser (also supported by mainstream browsers)
e.cancelBubble = true;
// Compatible syntax
if (e.stopPropagation) {
    e.stopPropagation();
} else {
    e.cancelBubble = true;
}
  1. Event delegation

The premise of event delegation is that the entrusted elements have the same event function. Multiple child elements can define the same event delegation in the parent element, which can improve the efficiency of web pages. The target object acquisition method in delegation is as follows.

// Mainstream browser
e.target;

// Old IE browser
e.srcElement;

// Compatible syntax
var target = e.target || e.srcElement;
  1. Block browser default behavior
// Mainstream browser
e.preventDefault();

// Old IE browser
e.returnValue = false;

// Compatible syntax
if (e.preventDefault) {
    e.preventDefault();
} else {
    e.returnValue = false;
}
  1. Obtain keyboard key code: e.keyCode;

Target and This

  • Target: target object, which is always the node object that originally triggered the event.
  • This: the current node object that triggers the event, which changes with the event bubble.

Screen object

The browser screen object records the information about the client display screen, which is often used to obtain the resolution and color information of the screen.

Window operation

// 1. Open a new window (the third parameter is empty, the small window is integrated with the browser, the third parameter is not empty, and the small window is separated from the browser)
var newWindow = open("url", "custom Name/target", "width=xx,height=xx,left=xx,top=xx", "replace");

// 2. Change the size of the window (only new windows can be operated)

newWindow.resizeTo(Width, Height);
// 3. Change the position of the window (only the new window can be operated)
newWindow.moveTo(x, y);

// 4. Close the window
 Any window.close();

Screen size

  • Browser full size: outerWidth/Height;
  • Browser document display area size: innerWidth/Height;
  • Display resolution size: screen.Width/Height;

History object

The browser history object records the visited history URL address.

  • Step n: history.go(n);
  • Step n of the page: history.go(n);
  • Page refresh: hisotry.go(0);

Location object

Browser location object, which records the URL related information of the current window, is often used to obtain and change the current web address.

  • Jump page: location="URL";
  • Refresh page: location.reload();
  • Jump back forbidden: location.replace("URL");

Navigator object

Browser information object, which is often used to obtain client browser type and operating system information.

Syntax: navigator.userAgent;

Document object

The Document object is part of the Window object and can be accessed through the window.document property.

Extended timer

Timers can produce effects such as dynamic clock, countdown and running lantern. They are divided into periodic timers and one-time timers. Their underlying principles are the same and can be converted to each other. They all use millisecond units for timing, in which the timer name saves the timer serial number.

//1. Turn on the periodic timer
timerName = setInterval(function () {
    Operation statement;
}, Millisecond time)

//2. Turn off the periodic timer
cleatInterval(timerName);

//1. Turn on the disposable timer
timerName = setTimeout(function () {
    Operation statement;
}, Millisecond time)

//2. Turn off the one-time timer
clearTimeout(timerName);

Expand cookies

Cookie Is a client data storage technology. It is a text format key value pair generated by the server and stored in the client file system. When the browser requests the page on the site again, it will automatically send the saved Cookie back to the server. With the rise of new technology, cookies will be eliminated gradually.

  • Get Cookie: document.cookie to get all readable cookies of the current site.
  • Cookie application: page customization, recording user login status, tracking user behavior, and saving specific global variables.
  • Disadvantages of cookies: the privacy security is poor. The browser can choose to disable cookies or delete cookies manually.
  • Cookie location: the cookie data of different sites are saved in different files, which are generally saved after encryption.
  • Cookie life cycle: specify the expires value to define the cookie life cycle, which is valid within the cycle and automatically destroyed after expiration.

Expand Webstorage

Webstorage is a new client storage technology. It has larger storage space, richer and easier to use interfaces, independent storage space and local storage content. It is divided into local level and session level.

  • localStorage (local level: permanently saved, can only be manually deleted)
  • sessionStorage (session level: destroyed as browser closes)
  • Setting data: local/sessionStorage. Attribute name = attribute value;
  • Get data: local/sessionStorage. Attribute name;
  • Delete a piece of data: local/sessionStorage.removeItem("property name");
  • Delete all data: local/sessionStorage.clear();
  • [note] old IE does not support Webstorage storage technology.

Expansion | composition of URL

URL (Uniform Resource Locator) is the Uniform Resource Locator. The complete URL consists of four parts: protocol name, domain name / host number, port number, file relative path, and sometimes parameter string.

  • Protocol: HTTP, HTTPS, FTP.
  • Domain name / host number: www.bilibili.com / 127.0.0.1.
  • Port number: HTTP default port number 80, HTTPS default port number 443, and the default port number can be omitted.
  • File relative path: the relative path of the accessed resource under the server, which is sometimes encrypted.
  • Query parameter: in URL? The subsequent content is often submitted for the user and transmitted to the server.

Expand window opening mode

// 1. Replace the current page and allow to go back
HTML: < a href="url">Content</a>
JS: open("url", "_self");

// 2. Replace the current page and do not go back
location.replace("url");

// 3. A new window is opened, which can be opened multiple times
HTML: <a href="url" target="_blank">Content</a>
JS: open("url", "_blank");

// 4. A new window can only be opened once
HTML: <a href="url" target="custom Name">Content</a>
JS: open("url", "custom Name");

// 5. Other functions of hyperlinks (link jump, anchor jump, file download, file loading, making phone calls, sending emails, writing embedded JS codes)
Writing inline JS code: <a href="javascript:JS sentence;"></a>

Tags: Javascript ECMAScript BOM ECMAScript6

Posted on Sun, 12 Sep 2021 15:04:06 -0400 by heepofajeep