The Browser Object Model (BOM) is the Browser Object Model. It provides objects that interact with the Browser window independently of content. The core Object is window.

DOM document Object Model:

  • DOM is about thinking of a document as an object
  • The top-level object of the DOM is document
  • DOM is primarily about manipulating page elements
  • DOM is a W3C standard specification

BOM Browser object model:

  • Think of the browser as an object
  • The top-level object of the BOM is window
  • BOM learns about objects that a browser window interacts with
  • BOM is defined by browser vendors on their browsers
  • BOM contains the DOM

A window object

Window is the base class of the client browser object model, and the Window object is the global object of the client JavaScript. A window object is essentially a separate window. For frame pages, each frame of the browser window contains a Window object.

Dual role:

  • 1. It is an interface for JS to access the browser window.
  • It is a global object. Variables and functions defined in the global scope become properties and methods of the window object (global variables = properties of the window: “window. The variable name “prints the value of the variable, and the function becomes the window method. You can omit the window when calling. The dialogs you learned earlier belong to window object methods, such as alert() and prompt().

1.1 Using the System Dialog box – Three ways of human-computer interaction

  • 1. Alert () : Identifies the alert box. Prompt messages are presented to the user by the browser. This method contains an optional prompt message parameter. If no parameter is specified, an empty dialog box is displayed.

  • 2. Confirm () : Select the confirmation dialog box. The prompt message is displayed by the browser to the user. The pop-up dialog box contains two buttons, indicating “OK” and “Cancel” respectively. This method returns true if the OK button is clicked; Click the Cancel button to return false. The Confirm () method also contains an optional prompt message argument, or an empty dialog box will pop up if no argument is specified.

  • 3. Prompt () : Enter the prompt box. Can receive user input information, and return the input information. The prompt() method also contains an optional prompt message argument, which, if not specified, brings up an input text dialog box with no prompt.

      var user = prompt("Please enter your user name");
      if(!!!!! user) {// Convert the input information to a Boolean value
        var ok = confirm("The user name you entered: \n" + user + "\n Please confirm."); // Enter the information to confirm
        if (ok) {
          alert("Welcome: \n" + user);
        } else {
          // Re-enter the information
          user = prompt("Please re-enter your username:");
          alert("Welcome: \n"+ user); }}else {
        // Prompt for input information
        user = prompt("Please enter your username:");
      }
Copy the code

1.2 Window Events

1.2.1 Window loading event window.onload

  • Window. onload is a window (page) loading event that is invoked when the document content (including images, scripts, CSS files, etc.) is fully loaded.
  • With window.onload, you can write JS code at the top of a page element, because onload waits until the page is fully loaded before executing the handler function.
  • Window. onload The traditional registration event can be written only once. If there are multiple registered events, the last window.onload takes effect.There are no restrictions if you use addEventListener
window .onload = function (){
// Write js code inside
}
/ / or
window.addEventListener ("load" , function() { 
// Write js code inside
});
Copy the code

1.2.2 Window loading event DOMContentLoaded

  • The DOMContentLoaded event is triggered only when the DOM is loaded, excluding stylesheets, images, Flash, etc.
  • If there are many pictures on the page, it may take a long time from user access to onload trigger, and the interactive effect will not be realized, which will inevitably affect the user experience. In this case, DOMContentLoaded event is appropriate.
  • DOMContentLoaded is when you load the DOM, you don’t have images, you don’t have flash, you don’t have CSS, you can load it faster than load
  • Le9 or above is supported;
document.addEventListener("DOMContentLoaded".function () {});Copy the code

1.2.3 Resize the Windowresize

  • Window. onresize is a handler that adjusts the window size to load the event and is called when triggered.
  • Note:

This event is triggered whenever the window size changes by pixels. We often use this event for reactive layout. Use window.innerWidth to get the current screen width

window.onresize = function () {};
window.addEventListener("resize".function () {});
Copy the code

1.3 timer

The Window object contains four timer specific methods, described in the following table, which can be used to implement timed or delayed code execution, and to design demo animations.

SetTimeout (callback function, delay time (milliseconds)); Call the function when the countdown ends

ClearTimeout (timer name) : Clears the setTimeOut timer.

SetInterval: The interval at which the callback function is executed

ClearInterval (timer name) : Clears the setInterval timer. The difference between:

  • The setTimeout() method is mainly used to delay code execution, while the setInterval() method is mainly used to execute code periodically. They can both design periodic actions, with the setTimeout() method suitable for executing an action at random and the setInterval() method suitable for executing an action at random.

  • The setTimeout() method does not perform an action at a fixed time interval. It is affected by the JavaScript task queue and only delays the execution of the action when there is no previous task. The setInterval() method is not limited by the task queue. It simply repeats the action at certain intervals. If the previous task has not been completed, setInterval() may jump the queue to execute the action on time.

2. The navigator object

The Navigator object stores basic browser-related information, such as name, version, and system. Window. navigator references this object and uses its properties to read basic client information.

The Navigator object contains information about the browser and has a number of properties, the most common being the userAgent, which returns the value of the User-Agent header of the server sent by the client.

The following front-end code can determine which terminal users open the page, to achieve the jump:

      if((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|
      Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS
      |Symbian|Windows Phone)/i))) {
       window.location.href = ""; / / cell phone
      }
      else {
       window.location.href = ""; / / computer
      }
Copy the code

3. Location object

The Window object gives us a location property that gets or sets the FORM’s URL and can be used to parse the URL. Because this property returns an object, we will also call this property a Location object.

URL: Uniform Resource Locator (URL) is the address of a standard Resource on the Internet. Every file on the Internet has a unique URL that contains information indicating where the file is and what the browser should do with it.

3.1 Properties of the location object

In the url, for example: www.baidu.com:8080/web/javascr…

3.2 Custom query string parameter Returns an object

/ / assume that the current URL: 'http://www.maxiaofei.com/Web/test.js?name=mafei&age=24&sex=m'

function getQueryObj(){
    let location = window.location;
    let queryStr = location.search.length > 0 ? location.search.substring(1) : ' ';
    let obj = {},item;
    let queryArr = queryStr.length > 0 ? queryStr.split('&') : []
    
    for(let i=0; i<queryArr.length; i++){ item = queryArr[i].split('=');
        obj[item[0]] = item[1]}return obj
}

getQueryObj()
{/ / ="
    name: 'maxiaofei'.age: 24.sex: 'm'
}
Copy the code

3.3 modify the location

Every time you change any property other than the hash of location, the page reloads with the new URL

window.location = 'http://www.maxiaofei.com'

location.search = '? name=mafei&age=18'

location.hostname = 'www.baidu.com'

location.pathname = 'web/html/a.html'

location.port = '1234'
Copy the code

Any changes other than the hash value will generate a new record in the browser’s history, which can be navigated to the previous page using the browser’s back button. You can disable this behavior with the replace() method. Pages opened with replace cannot go back to the previous page

// Try the following code in the browser console, the browser will not support rollback
location.replace('http://www.baidu.com')
Copy the code

3.4 Reloading

The page can be reloaded using the location.reload() method

Location.reload () : reload(possibly from cache)

Location.reload (true) : Reload (from the server)

The history object

The history object holds a history of the user’s Internet history from the moment the window is opened, and because history is a property of the Window object, every browser window, every TAB, every frame, Each has its own history object associated with a particular Window object. History usually has the following three methods and a property:

  1. history.go()

Receives an integer number or string argument: Jumps to the page whose most recent record contains the specified string

history.go('maixaofei.com')		// Search forward or backward for the specified string page
history.go(3)	// Jump forward to three records
history.go(-1)	// Jump backwards to a record
Copy the code
  1. history.forward()

Jump forward one page

  1. history.back()

Jump backwards to a page

  1. history.length

If it is the first page opened, then history.length == 0, which can be used to determine whether the currently opened web page is the first page opened in the window

The history object is rarely used in real development, but is found in some OA office systems.

Screen objects are not very useful objects

It is basically used to indicate the capabilities of the client, including display information outside the browser window, such as pixels and width, as shown in the following common attributes:

availHeight    // Screen pixel height minus system component height

availWidth     // The screen pixel width minus the system component width

availLeft        // The leftmost pixel value that is not occupied by system components

availTop       // Uppermost pixel value not occupied by system components

height          // Screen pixel height

width           // Screen pixel width
Copy the code

6. Other

6.1 Element visual area Client

ClientTop and element. clientLeft get the offset value of the visible area (which is essentially equal to the border value above and below the Element) rounded to an integer; Element.clientWidth and Element.clientHeight get the width of the viewable area (the width of the padding + Element content area, excluding the scroll bar)

6.2 Element offset(block-level element, read-only attribute)

  1. Element.offsetParent

Element.offsetParent is a read-only property that returns the nearest parent of the current Element.

  1. Element.offsetLeft && Element.offsetTop

Element.offsetLeft and element. offsetTop are read-only attributes that return the offset of the current Element relative to the left and top of the parent Element.

  1. Element.offsetWidth && Element.offsetHeight

Element.offsetWidth and element. offsetHeight are read-only attributes that return the width and height of an Element’s layout (including border, scroll bar, padidng, content block), and the value returned is a rounded integer.


6.2.1 Difference between offset and style

Offset:

  • Offset can get the style value in any stylesheet
  • The values obtained by the offset series are ununitless
  • OffsetWidth contain padding + + width, border
  • Properties such as offsetWidth are read-only and can only be obtained but cannot be assigned

So, we want to get the size of the element, offset is more appropriate

Style:

  • Style can only get style values from inline style sheets
  • Style.width returns a string with units
  • Style.width gets a value that does not contain the padding and border
  • Style. width is a read-write property that can be obtained or assigned

So, if we want to change the value of an element, we need to change the style

6.3 Scroll (to evaluate scrollable elements)

6.3.1 Element. The scrollTop and Element. ScrollLeft

Gets or sets the width of the rolled element (the distance from the top or left of the child element to the top or left of the current element’s viewable area)

Supplement:

  • The value is 0 for non-scrollable elements element. scrollTop and element. scrollLeft
  • If the value set to scrollTop (scrollLeft) is less than 0, the value of scrollTop (scrollLeft) will change to 0.
  • If the value set to scrollTop (scrollLeft) is greater than the maximum width of the element content, the value of scrollTop (scrollLeft) will be set to the maximum width (height) of the element.

6.3.2 Element. ScrollWidth && Element. ScrollHeight

  • Element. ScrollWidth and Element. ScrollHeight isRead-only propertyIs the width and height of the scrollable area of the element; It’s actually equal toClientHeight /clientWidth + Width of content not displayed on the screen;
  • Their values are equal to the minimum width required for the element to fit all the contents of the viewport without using horizontal scrollbars.
  • It is measured in the same way as clientWidth(clientHeight) : it contains the inner margin of the element, but does not include borders, margins, or vertical scroll bars (if present). It can also include the width of pseudo-elements, such as ::before or ::after.
  • If the content of an element can fit without a horizontal scroll bar, its scrollWidth is equal to clientWidth; (The minimum value is the element’s visual area width and height: clientWidth (clientHeight))