DOM => document object model
DOM object => host object
DOM works with HTML and XML
Three types of objects in JavaScript
-
Local Object Native Object
Object Function Array Number Boolean Error EvalError SyntaxError RangeError ReferenceError TypeError URIError Date RegExp Copy the code
A local object is an object that can be new directly, a local object that gives you built-in objects
-
Built-in Object Built-in Object
Global Math ECMA => isNaN parseInt Number decodeURI encodeURI Infinity NaN undefined Copy the code
Global does not exist in JavaScript, and these global methods belong to global
Both local and built-in objects are internal to ECAM
-
Host Object Host Object
The browser objects Window (BOM) and Document(DOM) -> DOM are included in the BOM and are now split apart. Why is it split apart because DOM is a W3C specificationCopy the code
The objects provided by the environment in which JS scripts are executed, browser objects, are called host objects. Due to the difference of each host, different JS scripts are executed, so compatibility problems may occur
-
model
A model is a set of methods, arranged in order to find the appropriate method to solve the corresponding problem
Document
Document is just an object that’s the big head of a document that has properties and methods in it
- Document. GetElementByid on
Ie8
The following is case insensitive inie8
Here’s what you can do according to the labelname
That gets this element - Document. The getElementsByTagName according to the tag name for a group of elements is returned array class
- Document. The getElementsByClassName according to the className for a set of elements is returned array class
- ByClassName is compatible with IE8
- Document. The getElementsByName according to label the Name for a group of elements is returned array class In principle, is must have the name array of tag but depending on the browser You can use as long as you write the name is not commonly used
- Document. querySelector retrieves the first of the current DOM from the CSS fetch element
- Document. QuerySelectorAll to CSS access elements to obtain a set of elements
- QuerySelector, querySelectorAll this two compatible with IE7 enterprises generally don’t let to use
- Performance problems exist
- Achilles heelThe DOM obtained is not updated in real time
- Like us
remove
If you delete this DOM element it’s going to stay in this pseudo-array
- Like us
Node in the tree
Nodes contain elements => elements in nodes are called element nodes => element nodes equal to DOM elements
Traverses the node tree element node tree
- ParentNodes If the parent node is obtained, the top level is Document
- ChildNodes obtains childNodes
- Element node = 1
- Attribute node = 2
- Text node test = 3
- Comment node comment = 8
- document = 9
- documentFragment = 11
- lastChild firstChild
- nextSibling previousSibling
Walk through the element node tree
- ParentElement => The top level is Html
IE9 and below are not supported
- children
IE7 and below are not supported
- childElementCount = children.length
IE9 and below are not supported
- firstElementChild lastElemntChild
IE9 and below are not supported
- nextElementSibling previousElementChild
IE9 and below are not supported
Why is the top level of parentNodes document and parentElement HTML?
Because document is the document node,HTML is the element node,parentElement is the method to get the element node, the parent of HTML is the document node, not the element and HTML is the largest element
Get element compatibility solutions
/ * * *@description: Gets all child elements *@param {*} node
* @return {*}* /
function getChildElementNodes(node) {
var len = node.childNodes.length,
childNodes = node.childNodes,
nodeArr = [],
elem;
for (var i = 0; i < len; i++) {
elem = childNodes[i]
if (elem.nodeType === 1) {
nodeArr.push(elem)
// nodeArr[nodeArr['length']] = elem
// nodeArr['length']++}}return nodeArr;
}
/ * * *@description: Gets the first element node *@param {*} node
* @return {*}* /
function getFirstELementChildNode(node) {
var elem = node.firstChild
while(elem && elem.nodeType ! = =1) {
elem = elem.nextSibling
}
return elem
}
/ * * *@description: Gets the last element node *@param {*} node
* @return {*}* /
function getLastELementChildNode(node) {
var elem = node.lastChild
while(elem && elem.nodeType ! = =1) {
elem = elem.previousSibling
}
return elem;
}
/ * * *@description: Gets the next sibling element *@param {*} node
* @return {*}* /
function getNextSiblingElementNode(node) {
var elem = node.nextSibling
while(elem && elem.nodeType ! = =1) {
elem = elem.nextSibling
}
return elem
}
/ * * *@description: Gets the previous sibling element *@param {*} node
* @return {*}* /
function getPreviousSiblingElementNode(node) {
var elem = node.previousSibling
while(elem && elem.nodeType ! = =1) {
elem = elem.previousSibling
}
return elem;
}
Copy the code
Property methods of nodes
Element node =1Attribute node =2Text node test =3Comment node comment =8
document = 9
documentFragment = 11
// ------------------------GetAttributeNode () gets the attributes node Attributes gets the set of attributes => class arrayCopy the code
- NodeName Specifies the nodeName of the element node
A capital
read-only
- NodeValue nodeValue
Can be read
Can write
- Element nodes are useless
nodeValue
attribute - Property comment text is available
- Element nodes are useless
- Value Gets the value of the attribute node
- NodeType indicates the nodeType
read-only
- HasChildNodes whether the element hasChildNodes
The DOM tree structure
DOM objects are very popular, and each DOM is an instantiated object
DOM manipulation depth
- getElementById()
- GetElementById () is available only on document.prototype
- getElementsByName()
- GetElementsByName () is available only on document.prototype
- getElementsByTagName() | getElementByClassName() | querySelector | querySelectorAll
- Document. The prototype and the Element. The prototype has getElementsByTagName () | getElementByClassName () | querySelector | querySelectorAll
- document.body
- Gets the body element
- On the HTMLdocument
- document.head
- Gets the head element
- On the HTMLdocument
- document.title
- Get the text inside the title, not the title element
- On the HTMLdocument
- document.documentElement
- Getting HTML elements
- On the Doducment
/ / sample
// 1. When we want to select some tags under a certain ID, we can use the DOM prototype relationship to select
document.getElementById('box').getElementsByTagName('div') // Since element. prototype also has getElementsByTagName, this is optional
Copy the code
A small case
/ * * *@description: Gets any child element *@param {Number} The child element index does not return all *@return {*} Any child element */
HTMLElement.prototype.getChild = function () {
// var nodes = [],
var nodes = {
splice: Array.prototype.splice,
push: Array.prototype.push,
length: 0
},
arg1 = arguments[0],
len = this.childNodes.length,
child = this.childNodes
for (var i = 0; i < len; i++) {
if (child[i].nodeType === 1) {
nodes[nodes.length] = child[i]
nodes.length++
}
}
return arg1 ? nodes[arg1] || nodes : nodes
}
/ * * *@description: Gets the parent node of layer N *@param {Number} The obtained NTH level is not passed to the previous level, and the index greater than the top level is returned to the last level *@return {*} The parent element of layer N */
HTMLElement.prototype.getParent = function () {
var parentNode = this,
oldParentNode,
arg1 = arguments[0] | |1
while (arg1 && parentNode) {
oldParentNode = parentNode
parentNode = parentNode.parentNode;
arg1--
}
return parentNode || oldParentNode;
}
Copy the code
Node creation
-
Document.createelement Creates the element node
- Document.prototype
-
Document.createtextnode creates a text node
- Document.prototype
-
Document.createcomment Creates a comment node
- Document.prototype
-
Parent. appendChild Adds child nodes
- Node.prototype
- Dynamically add nodes, dynamically cut nodes
- If we get a tag in the document and appendChild goes to the specified node, we find out which node went to the specified node.
- In fact, when we use appendChild, what it does is, cut it and copy it in
- The arguments to this method must be nodes or elements
-
C.nsterbefore (a,b) inserts the node
- Node.prototype
- Insert node A into c before node B
-
Parent.removechild () removes child nodes
- Node.prototype
- It’s actually cutting the child node, it’s not deleting the node, it’s still in memory, but it’s no longer in the DOM structure, so it can’t delete the DOM object that’s in memory
-
Div.remove () removes the node
- Node.prototype
- Delete the node and delete the DOM object
-
Parent. ReplaceElement (newEle,oldEle) replaces nodes
- Node.prototype
-
div.innerHTML
- HTMLElement.prototype
- Element.prototype
- Can read but write
- Assign Value Append Value Adds an HTML string
-
div.innerText
-
Older versions of Firefox do not support textContent instead of textContent older versions of IE do not support textContent
-
HTMLElement.prototype
-
Div. SetAttribute (‘type’,’value’) sets the attribute
- Element.prototype
-
Div.getattribute (‘type’) gets the attribute
- Element.prototype
-
Div. dataset gets the property
-
Gets the custom property data-*
<div data-name='zs' data-age='18'>I am a div</div>{name:' ZS ',age:'18'}}Copy the code
-
-
Document. CreateDocumentFragMent () to create document fragments (pieces) * * * *
- Reduce reflux
How does an element become an element node
There must be some methods in element nodes such as nodeName nodeType attribute
When we select an element using a selector, it goes through those steps, for example div
- Element => instantiate object => node
- That is, when div is selected it will instantiate new HTMLDivELement, and that’s when the DOM object is created, and the DOM object is equal to the DOM node
- This object is stored in memory, and because it is a reference type, it is stored in the heap.
backflow
Each time the DOM re-adds an element node, the geometry data (the element’s position in the browser) is recalculated, which is called backflow
Rolling distance height, visual size
The rolling distance
-
Window. pageXOffset window.pageYOffset Gets the scroll distance of X axis and Y axis
- Internet Explorer 9 and later are not supported
- The corresponding attributes of Internet Explorer 9 and Internet Explorer 8 are
document.documentElement.scrollTop
document.documentElement.scrollLeft
document.body.scrollTop
document.body.scrollLeft
- What’s unusual is that
window.scrollX
window.scrollY
// Compatibility encapsulation function getScroll() { if (window.pageXOffset ! = =undefined) { return { left: window.pageXOffset, right: window.pageYOffset } } else { return { left: document.body.scrollLeft + document.documentElement.scrollLeft, top: document.body.scrollTop + document.documentElement.scrollTop } } } Copy the code
The size of the browser’s viewable area (window width and height)
-
General: window. The innerWidth/window. InnerHeight
- Gets the viewable area size width/height
-
IE9/IE8 and below:
- The standard model
- docuemnt.docuemntELement.clientWidth/clientHeight
- Gets the width/height of the viewable area
- Quirks mode
- document.body.clientWidth/clientHeight
- Gets the width/height of the viewable area
// Get the browser viewable area size compatibility package function getViewPortSize() { if (window.innerWidth) { return { width: window.innerWidth, height: window.innerHeight } } else { if (document.compatMode === 'BackCompat') { // If the current browser is in weird mode return { width: document.body.clientWidth, height: document.body.clientHeight } } else { return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight }; }}}Copy the code
- The standard model
Get the entire document size (width and height of the entire HTML)
- document.body.scrollWidth/scrollHeight
- Gets the width/height of the document
- document.documentElement.scrollWidth/scrollHeight
- Get the width and height of the document IE567
Gets the size position of the element
- oBox.getBoundingClientRect
- The advantage is basically all sizes can be obtained, the fatal disadvantage attribute is not real-time
- Ie 678 has no width and height
{
bottom: 150
height: 120
left: 30
right: 150
top: 30
width: 120
x: 30
y: 30
}
Copy the code
Gets the position of the element
- Elem. OffsetTop/offsetLeft distance to the left of the top of the elements of the current distance
- Get the current element to the last positioned parent element,** look up if the parent element is not positioned,** find the body if all the parents are not positioned
- Elem.offsetparent Gets the last parent element with a location and finds the body if none
Operation scroll bar
- Window. Scroll/scrollTo scrollBy operating scroll bar the first parameter is the X axis the second parameter is the Y axis
- Scroll /scrollTo to the absolute position in the document
- ScrollBy Specifies the distance to scroll (the current scrollbar distance plus the parameter distance)
Browser weird mode and standard mode
! DOCTYPE html
Browsers have their own compatibility mode, the browser default compatibility format (backward compatibility). Browser manufacturers generally compatible with 5 versions, if you write DOCTYPE HTML must comply with the W3C specification, if not! DOCTYPE HTML is compatible with the browser’s own rules
Write! DOCTYPE HTML is standard mode, not DOCTYPE HTML is weird mode
Verify whether it is weird or standard
document.compatMode
/ / standard model | | quirks mode
// "CSS1Compat" || "BackCompat"
Copy the code
Read and write style properties
DOM indirectly manipulates CSS note: It does not manipulate stylesheets. DOM cannot manipulate stylesheets
- Elem. Style. CSS properties
- Can read but write
- Note that small humps must be used if two or more CSS attribute words appear as follows:
borderColor
- The value must be a string of characters such as:
elem.style.borderWidth = '10px'
- Conforming values must be disassembled as follows:
1px solid #fff
Need to disassembleborderWidth = '1px'; borderStyle = 'solid'
Etc. - Reserved words must be preceded by
css
Such as:elem.style.cssFloat = 'left'
- Style Gets the collection of styles that the current element can set
- Window.getcomputedstyle (Element,null) gets the element’s calculation style attribute
getComputedStyle
The second argument to get the pseudo-element style if written, for example:getComputedStyle(element,'after')
- Default style property if the element does not set this style property
- The corresponding attribute is not supported by Internet Explorer 8 or below
- element.currentStyle
Setting the Class attribute
If there are multiple styles, change the class name directly
- Element. className Gets the class attribute, which is readable and writable
The event
Bind event = bind event handler
Onclick = function(){event feedback}
Bind event event handlers
Event + event handler = front-end interaction interaction experience
- onclick = function(){}
- Handle to onclick at this point
- Onclick = function(){} Event handle
- Odiv.onclick = function(){} The binding form of the event handle
- onclick = null
- Element.addeventlistener (event type, event handler, Boolean)
- Element. attachEvent(event type, event handler)
- Element. The removeEventListener (event types, event handler)
- Ie8 and below Element. detachEvent(event type, event handler)
Event state bubbling and capturing
The default state of the event is bubble state
What is event bubbling?
Event bubbling is the process of event bubbling from inner elements to outer elements
- Event Indicates the compatibility of event objects
- event || window.event
- Ie8 and below do not support W3C standards
- Event. cancelBubble = true Prevents events from bubbling in IE8 and below
- Event. preventDefault Prevents default events IE8 and below do not support W3C standards
- Event. returnValue = false blocks default events Ie8 and below
- Return false Prevents default events that are highly compatible but not commonly used
Flow of events
Describes the sequential bubbling capture of events received from the page
- Event Bubbling (IE)
- Event Capturing by Netscape
Three phases of the event flow
The event capture phase is in the target phase event bubbling phase
- First catch in bubbling
- In the target phase, event sources are not bubbling or catching problems and execute in the order of code execution
DOM level issues
The event model
Specification of the event model
It can be thought of as a three-stage specification
-
DOM0
- onXXX = fun
- elem.onXXX = fun
-
DOM1
- No event model is defined
-
DOM2
- AddEventListener (three parameters) W3C specification
- RemoveEventListener (event type, event handler)
The event object
Each event handler has an event object, event
- The event handler has an event object as an argument
- Ie8 and below event objects are in Windows
- Event. The target | | event. The srcElement is the event source
- ScrElement IE9 and below
Event broker, event delegate
Event broker, event delegate, is an event broker that uses the bubbling of events to bind events to the parent element and get the event source that triggers the event, thus greatly improving performance and adding and deleting child elements in real time
parentEle.onclick = function(e){
var e = e || window.event,
tar = e.target || e.currentElement
}
Copy the code
- Takes the index of the event source in the element list
parentEle.onclick = function(e){
var e = e || window.event,
tar = e.target || e.currentElement
for(var i = 0; i < len; i++){
if( oList[i] === tar ){
console.log(i)
}
}
}
// The best solution
parentEle.onclick = function(e){
var e = e || window.event,
tar = e.target || e.currentElement
Array.prototype.indexOf.call(oList,tar)
}
Copy the code
- What exactly is an event broker
- The same callback function is bound to multiple event bindings, such as 50 LI binding events. If the binding is repeated, 50 callback functions are bound and the new tag has no event
The mouse behavior
Coordinate system
-
Event. clientX/Y Coordinates of the current visible area where the mouse is located (not including the distance of the scroll bar)
-
LayerX /Y is the same as pageX/Y,IE11 is the same as clientX/Y below
-
ScreenX /Y Specifies the screen coordinates where the mouse is located
-
X/ y same as clientX/ y, FF(firefox not supported)
-
PageX /Y The coordinates of the mouse in the document (including the distance of the scroll bar)
- Ie9 and below not supported (Jquery)
-
OffsetX /Y Coordinates of the mouse position relative to the block element
-
Contains borders,safari does not contain borders is not recommended
-
Gets the document offset IE8 and below
- document.documentELement.clientLeftt
Mouse events
Mouse events are usually simulated using mouse down lift events
-
Mousedown Indicates the event that the mouse is pressed down
-
Mouseup Mouse lift event
Mouse event Several important properties of the event object
- Button Determines which mouse button triggers the current event
- Typically, advanced browsers are 0, 1, 2, left, middle, and right
- Button Determines which mouse button triggers the current event
-
Contextmenu Right-click menu event
- It is usually disabled for event.prventDefault
-
Mouseover mouseover
-
Mouseout Mouse moves out
-
Mouseenter Moves the mouse
- Mouseover differs from mouseover in that it does not bubble and mouseEnter works on the bound element, mouseout works on the bound element and all its children
-
Mouseleave Mouse out
The input event
- IE9 and the following onpropertychange input feedback
- IE9 above onInput feedback
- Onchange loses focus feedback Does not feedback if the value of the lost focus is the same as that of the lost focus
- Onfocus comes into focus
- Lose focus
Custom events
Htmlelement. prototype = bindEvent = bindEvent = bindEvent
// Why add it to the HTML prototype
HTMLElement is the direct parent of the element node. For example, HTMLDivElement, we can see that its direct parent is HTMLElement, so the definition of the prototype of HTMLElement is the most reasonable
// 2. What events do we need to bind
/ / 3. We came up with a custom Event must use the constructor Event https://developer.mozilla.org/zh-CN/docs/Web/API/Event see the MDN
HTMLElement.prototype.bindEvent = function(type,callBack){
var elem = this.// Store the element
_event = new Event(type);
elem.addEventListener(type,callBack,false)
function dispatch(){
elem.dispatchEvent(_event)
}
function remove(){
elem.removeEventListener(type,callBack,false)}return {
dispatch,
remove
}
}
Copy the code
Monitor DOM node changes
MutationObserver uses constructors to listen for changes to DOM nodes
- MutationObserver. Prototype. Disconnect stop listening/stop listening
- MutationObserver. Prototype. Observe the DOM changes through the callback function to receive notifications
- MutationObserver. Prototype. Delete akeRecords notice the queue to deal with the notification
- See: developer.mozilla.org/zh-CN/docs/…