JS summing up (5) - Bom and Dom

1. Good

1.1 window

BomThe core object is window, both showing an example of a browser for an interface to access the browser window, is js global object, all the global scope of the definition of methods and variables will become their property.
be careful:

  1. Become the windowobject properties of methods and variables can not be used deleteto delete
  2. Undefined variable access would be an error, while using windowindirect access is not (only vardefined)

1.2 iframe

  1. Each iframehas its own windowobjects, windowobject has a nameproperty. By window.frames[index]or window.frames[frameName]to access the corresponding windowobject.

  2. Since each iframeof the windowpoints to the current iframein windowthe object, thus introducing an topobject, this object has always point to the outermost frame i.e. the browser window.

  3. And topthe object is opposite to the parentobject, which points to the current iframein the direct upper frame, and if not then the topobject are equal.

  4. In order to correspond to the target, the introduction of an selfobject is the windowobject itself, may be used interchangeably.

So to prevent the page is iframethe following method:

window.onload = function () {
    if (top !== self) { // 判断当前window是否在最上层即可
        top.location.href = self.location.href
    }
};

1.3 location

It provides useful information about the current folder window plant documentation and some navigation functions.
Commonly used methods and properties to:

Property or method Explanation
hash The contents of the URL after the #
host Domain name and port number of the URL
protocol The URL http protocol
href Full URL path
search The URL? Behind the content
assign() And location.href = 'xxx' same
replace() Open a new page and can not be returned
reload() Re-open the current page

1.4 Other

  1. navigator: Used to detect the browser and system information
  2. screen: Take a screen and window information
  3. history: Browse window for recording information

For security, historythe urlcan not be obtained, only call go()or back()' 或forward () `to go forward and backward.

H5 offers pushStateand popStateevents for manipulating the historyrecord stack

The following code can prevent the browser fallback:

window.onload = function () {
    pushState ()
    window.addEventListener('popstate', function (e) {
        pushState ()
    })
};

function pushState () {
    const state = {
        title: 'title',
        url: '#'
    }
    window.history.pushState(state, 'title', '#')
}

2. Judgment

2.1 Node Type

More commonly used on the following categories:

  1. documentType: docmentitself that represents the entire document
  2. elementType: for indicating HTMLelement
  3. textType: This plain text, not very common, usually with elementthe type of call innerHTMLor innerTextachieve
  4. documentFragmentType: for storing Domnode for adding a one-time Domoperation, improve performance

All types Nodecan visit or call the property or method of its own

2.2 Operation

Only common column

Property or method Explanation
querySelector() Similar CSS selectors
children Get all child elements
classList Class acquisition element, can be operated via add, contains, remove, toggle
innerHTML / innerText Gets or modify elements inside the HTML or Text
document.readyState Two values ​​loading and complete, for monitoring the state of the document is loaded
offsetWidth/offsetHeight Get the elements of the actual width and height
offsetWidth/offsetHeight Gets the element content width and height (frame not included)
offsetTop/offsetLeft Get away from the parent element of the element
getBoundingClientRect() Get a page element distance viewport location has width and height of elements (including the border)

2.3 traversal

2.3.1 Depth-First
  1. NodeIterator
    parameters: start node traversal, the type of access nodes, the node filters
const iterator = document.createNodeIterator(document.documentElement, NodeFilter.SHOW_ELEMENT, null)
let node = iterator.nextNode()
while (node) {
    console.log(node.tagName)
    node = iterator.nextNode()
}
  1. TreeWalker
    parameters, supra
    use: as above
    in addition to nextNode()and previousNode()to the methods, provides an additional parentNode(), firstChild(), lastChild, nextSibling(), previousSibling()or the like, for providing the respective directions of traversal, no longer limited to the depth-first
2.3.2 Breadth-First
const nodeList = [document.documentElement]
while (nodeList.length) {
    const node = nodeList.shift()
    nodeList.push(...node.children)
    console.log(node.tagName)
}

3. Event

Events provide Javascriptthe HTMLinteractive features between documents, it is a document or a browser instantly find specific interaction with the listener can make the reservation, is designed to model the Observer pattern.

3.1 event stream

It describes the sequence of events is received from the page.

  1. Event bubbling: elements layer by layer from the trigger event at the beginning of the process to spread to the higher top
  2. Event Capture: From the topmost layer by layer process began to spread down the elements of a trigger event
  3. Event flow: the capture phase of the order for the event, in the target phase, the event bubbling phase

3.2 Event Handler

  1. Dom0 stages: definition of the front cover behind
const btn = document.getElementById('btn')
btn.onclick = function () {
    console.log(1)
}
btn.onclick = function () {
    console.log(2) // 2
}

Delete events:

btn.onclick = null
  1. Dom2 level: bind more can be triggered simultaneously, triggering order to define the order
const btn = document.getElementById('btn')
btn.addEventListener('click', function () {
    console.log(1) // 1
})
// true表示捕获阶段触发,btn是事件触发起始元素,不存在捕获冒泡阶段,仍然按定义顺序触发
btn.addEventListener('click', click, true) 
function click() {
    console.log(2) // 2
}

Delete events:

// 匿名函数定义的事件无法移除
btn.removeEventListener('click', click)

3.3 event object

Property or method Explanation
currentTarget Binding element event handlers
target Element that triggered the event
preventDefault() Prevent the default event triggers
stopPropagation() Stop event bubbling
eventPhase Get event the stage. 1. Capture, 2 target, 3. Bubbling

3.4 Event Types

List only a few common page-level event

Event Method Explanation
window.onload() Page has been loaded trigger, including images, files and other resources
document.DOMContentLoaded Dom after the completion of construction of the trigger (the browser refresh button also)
window.beforeunload Front page unload trigger
window.hashchange When the page URL changes occur to trigger hash

3.5 event delegation

Specify an event handler to manage all type of events, use event bubbling to solve the problem of too many event handlers.

<ul id="ul">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
document.getElementById('ul').addEventListener('click', function (e) {
    console.log(e.target.innerText)
})

3.6 event simulation

Simulation process: create an event => Initialize event object => trigger event

<ul id="ul">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
const ul = document.getElementById('ul')
ul.addEventListener('click', function (e) {
    console.log(e.target.innerText)
})
const event = document.createEvent('MouseEvents')
event.initEvent('click', true, true)
ul.firstElementChild.dispatchEvent(event)
Released six original articles · won praise 0 · Views 80

Guess you like

Origin blog.csdn.net/weixin_44844528/article/details/104871686