1. Good
1.1 window
Bom
The 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:
- Become the
window
object properties of methods and variables can not be useddelete
to delete - Undefined variable access would be an error, while using
window
indirect access is not (onlyvar
defined)
1.2 iframe
-
Each
iframe
has its ownwindow
objects,window
object has aname
property. Bywindow.frames[index]
orwindow.frames[frameName]
to access the correspondingwindow
object. -
Since each
iframe
of thewindow
points to the currentiframe
inwindow
the object, thus introducing antop
object, this object has always point to the outermost frame i.e. the browser window. -
And
top
the object is opposite to theparent
object, which points to the currentiframe
in the direct upper frame, and if not then thetop
object are equal. -
In order to correspond to the target, the introduction of an
self
object is thewindow
object itself, may be used interchangeably.
So to prevent the page is iframe
the 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
navigator
: Used to detect the browser and system informationscreen
: Take a screen and window informationhistory
: Browse window for recording information
For security, history
the url
can not be obtained, only call go()
or back()' 或
forward () `to go forward and backward.
H5 offers pushState
and popState
events for manipulating the history
record 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:
document
Type:docment
itself that represents the entire documentelement
Type: for indicatingHTML
elementtext
Type: This plain text, not very common, usually withelement
the type of callinnerHTML
orinnerText
achievedocumentFragment
Type: for storingDom
node for adding a one-timeDom
operation, improve performance
All types Node
can 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
- 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()
}
- TreeWalker
parameters, supra
use: as above
in addition tonextNode()
andpreviousNode()
to the methods, provides an additionalparentNode()
,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 Javascript
the HTML
interactive 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.
- Event bubbling: elements layer by layer from the trigger event at the beginning of the process to spread to the higher top
- Event Capture: From the topmost layer by layer process began to spread down the elements of a trigger event
- Event flow: the capture phase of the order for the event, in the target phase, the event bubbling phase
3.2 Event Handler
- 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
- 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)