Basic correlation between Web APIs and JS
- Composition of JS: JS syntax DOM BOM
- Web APIs: DOM BOM
API and Web apis
-
API: Application programming interface, which is a set of predefined functions
Simple understanding: is a tool to achieve the desired function
-
Web API: A set of apis (BOM and DOM) for browser functionality and page elements provided by the browser
DOM ()
I. Introduction to DOM
DOM tree document: A page is a document. Document element: all the tags in the page. Element node: All the content in the page is nodes
2. Get elements
How do I get web elements?
1. Get the getElementByld() method based on ID
<div id="time">2020-11-25</div> <script> //1. //2. Get gets the element by camel name //3. Var timer = document.getelementById ('time'); var timer = document.getelementById ('time'); console.log(timer); console.log(typeof timer); //5.console.dir(timer); Print the element object we return for a better view of its properties and methods console.dir(timer); </script>Copy the code
2. Get the getElementsByTagName() method by tag name — returns a collection of objects with the specified tag name
- Returns a collection of retrieved elements stored as a pseudo-array
- If there is only one LI in the page, it will return a pseudo-array
- An empty pseudo-array is returned if the element is not present on the page
To obtain an element (parent) within all of the specified tag name child element element. The getElementsByTagName (‘ tag name)
3. Obtain it through the new method of HTML5
Document.queryselector (' selector ')
// Returns the first element object according to the specified selectorDocument. GetElementsByClassName (' the name of the class)
// Returns a collection of element objects based on the class nameDocument. QuerySelectorAll (' selector ')
// Returns a collection of all element objects for the specified selector
4. Get special elements (body, HTML)
- For the body:
document.body
- Get the HTML:
document.documentElement
3. Event basis
1. Event elements: Event source Event type Event handler
- Event source: the object on which the event is triggered as: button
- Event type: How to trigger? What event? For example, onclick is a mouse pressed over the keyboard
- Event handler: Done by way of a function assignment
2. Perform the event steps
- Obtaining event Sources
- Register events (bind events)
- Add event handlers (take the function assignment method)
4. Operation elements
1. Change the element button
element.innerText
// The content from the start position to the end position, but it removes HTML tags as well as whitespace and newlineselement.innerHTML
// All content from start to end includes HTML tags with Spaces and line breaks
The difference between:
- 1. InnerText does not recognize HTML tags. Non-standard whitespace and line feeds are removed
- The W3C standard reserves Spaces and line feeds for HTML tags
These two attributes are read and write to get the contents of the elementCopy the code
2. Attribute operations of common elements
<button ID =" LDH "> </button id="zxy"> </button><br> <img SRC ="images/link.jpg" Alt ="" title=" Andy Lau "> // Modify the element attribute SRC //1. Var LDH = document.getelementById (' LDH '); var zxy = document.getElementById('zxy'); var img = document.querySelector('img'); Zxy.onclick = function() {img.src = 'images/zhang.jpg'; Img. Title = 'xueyou Cheung '; } ldh.onclick = function() { img.src = 'images/link.jpg'; Img. Title = 'Andy Lau '; } </script>Copy the code
Style attribute operation element.style inline style operation element.className className style operation
Note:
- JS styles take the camel name fontSize backgroudColor
- The JS modification sytle style operation results in a high CSS weight for inline styles
- ClassName directly changes the element’s className, overwriting the original className
5. Exclusivity Kills everyone and keeps him
<body> <button> button 1</button> <button> button 2</button> <button> button 3</button> </button> <button> button 5</button> <script> var btns = document.getElementsByTagName('button'); for (var i = 0; i < btns.length; I ++) {BTNS [I]. Onclick = function() {var I = 0; i < btns.length; i++) { btns[i].style.backgroundColor = ''; } this.style.backgroundColor = 'pink'; } } </script> </body>Copy the code
6. Customize attributes
- Get property values
Attributes element.
Element. The getAttribute (' property ')
- Setting property values
Element. attribute =' value '
Element.setattribute (' attribute ', 'value ')
- Remove the attributes
Element. RemoveAttribute (' property ')
7.H5 Custom attributes
The purpose of custom attributes is to save and use data, some of which can be saved to a page rather than a database
-
Setting H5 Custom attribute Specifies that the custom attribute date- begins as the attribute name and assigns a value
<div data-index="2" data-list-name="andy"></div> Copy the code
-
Gets H5 custom attributes
Element. getAttribute(‘ attribute ‘) H5 Add element.dataset. Index or element.dataset[‘index’]
Note:
- A dataset is a collection containing all the custom attributes starting with data
- If the custom attribute has more than one – join word take the hump nomenclature
console.log(div.dataset.listName)
5. Node operations
1. Why learn node operation: it is logical, but slightly less compatible
- Get elements using methods provided by the DOM
- Get elements using node hierarchies
In the DOM, nodes use node
- NodeType nodeType nodeName nodeName nodeValue nodeValue
- Element node 1 Attribute node 2 Text node 3
- The element node is the primary operation
3. Node hierarchy Father-son and elder brother hierarchy
- The parent node
node.parentNode
Returns the nearest parent of the element and returns null if no parent is found
- Child nodes
parentNode.childNodes
You get text nodes element nodes and so onparentNode.children
Nonstandard is a read-only property that returns all child element nodesparentNode.firstChild
Returns the first node, either a text node or an element nodeparentNode.lastChild
Returns the last node whether it is a text node or an element nodeparentNode.firstElementChild
Returns the first child elementparentNode.lastElementChild
Returns the last child element // and capricious problem above IE9 // written in actual developmentconsole.log(ol.children[0])
First child elementconsole.log(ol.children[ol.children.length - 1])
The last child element
3. Sibling nodes
node.nextSibling
You get the next sibling the text node the element node and so onnode.previousSibling
You get the last sibling the text node the element node and so onnode.nextElementSibling
You get the next sibling element nodenode.previousElementSibling
The result is the last sibling element node
4. Create a node
document.createElement('tagName')
- Add a node
node.appendChild(child)
Node parent child appends elements similar to push Node.insertbefore (child, specify element)
Specifies that an element is inserted before a child element
Add a new element to the page: 1. create element 2. add element
5. Delete the node
node.removeChild(child)
<a href='javascript:; '> delete < / a >
Clone node.clonenode ()
- If the parenthesis argument is empty or false, shallow copy copies only the tag and not the contents inside
- If the parenthesis argument is true, deep copy is full copy
7. Three dynamically created element differences
document.write()
If the page document flow has finished loading, the page will be redrawnelement.innerHTML
Create multiple elements more efficiently (don’t concatenate strings, concatenate arrays)document.createElement()
Creating multiple elements is slightly less efficient, but the structure is clearer
DOM focus core – event level
1. Register events (bind events)
- Traditional registration: with uniqueness, only one handler can be set for each element and event. The last registered handler overrides the previous one
- Method listener registration:
Elements. The addEventListener (type, the listener, useCapture [])
Features: Multiple listeners can be registered for the same element and event
-
Type: Event type string with ‘ ‘such as click, mouseover and not on
-
Listener: An event handler that is called when an event occurs
-
UseCaoture: Optional, a Boolean value, false by default
Ie9 previous version: attachEvent(‘onclick’, callback function)
Delete event (unbind event)
How to delete an event
- Traditional registration:
eventTarget.onclick=null
- Method listener registration:
eventTarget.removeEventListener(type,listener[,useCapture])
- Previous versions of Internet Explorer 9:
DetachEvent ('onclick', callback function)
DOM event flow: the process of event propagation
Capture stage Target stage bubbling stage (stones thrown into water)
4. Event object
- An event is an event object written inside the parentheses of our listening function as a parameter
- The event object only exists when it has an event and it’s created by the system for us and we don’t need to pass parameters
- So an event object is a collection of data that we call events that are related to events such as a mouse click that contains information about the mouse, the mouse coordinates and if it’s a keyboard event that contains information about the keyboard event such as determining which key the user pressed
- The event object can be named something else like Event, EVT, e
- Compatibility problem Internet Explorer 678 passes
window.event
Common properties and methods for event objects
E.target returns the object (element) that triggered the event. This returns the object (element) that bound the event.
Difference: e.target returns the element that was clicked on. This returns the element that was bound to the clicked event
Compatibility:
- With ie
e.srcElement
Gets the object that triggers the event e.type
Returns the event object type- Prevents default actions (events) to prevent links from jumping or submit buttons from being submitted
e.preventDefault()
- Lower version browser
e.returnValue
— Attributes or exploitsreturn false
It also prevents notice that the following code does not execute and is limited to traditional registration
5. Prevent bubbling
1. Two ways to prevent events from bubbling
- e.stopPropagation(); / / standard
- e.cancelBubble=true; //ei678
2. Compatibility solution to prevent event bubbling
if(e && e.stopPropagation){
e.stopPropagation();
}else{
window.event.cancelBubble = true;
}
Copy the code
Vi. Event delegation (agent, delegation)
The event delegate principle: Instead of setting an event listener for each child node, place the event listener on its parent node and then influence the setting of each child node using the bubbling principle
What event delegates do: Manipulate the DOM only once, improving performance
7. Common mouse events
- Disable the right mouse button menu:
contextmenu
- Disable mouse selection:
selectstart
2. MouseEvent object: MouseEvent KeyboardEvent object: KeyboardEvent
e.clientX/Y
Returns the x and y coordinates of the viewable areae.pageX/Y
Returns the x and y coordinates relative to the document pagee.screenX/Y
It returns the x and y coordinates relative to the computer screenmousemove
The mouse movesmousedown
The mouse clickmouseup
Release the mouse
Common keyboard events
- Keyboard event object:
KeyboardEvent
- Onkeyup Triggered when a keyboard key is released
- Onkeydown Triggered when a keyboard key is pressed
- Onkeypress is triggered when a keyboard key is pressed but it does not recognize function keys such as CTRL, Shift, and arrows
The execution sequence of the three events is Down >press> Up
2. The keyCode property returns the ASCII code value of the key to determine which key the user presses
Keydown and KeyPress in a text box: The event is triggered before the text falls into the text box
BOM
I. BOM Overview
- When the BOM browser object model interacts with the browser object
- The BOM component window object is the browser’s top-level object global variable, and all functions become methods on the properties of the Window object
BOM>DOM
Common events of window objects
1. Window loading event
window.onload=function(){}
window.addEventListener('load',function(){})
The most popular way to write itdocument.addEventListener('DOMContentLoaded',function(){})
Once the DOM element is loaded, the falsh CSS without the image is executed
Page contents such as load are loaded, including DOM elements, images, Flash and CSS
2. Resize the window
window.onresize=function(){}
window.addEventListerner('resize',function(){})
window.innerWidth
Gets the width of the current screen
Three, timer
1. Two types of timers
setTimeout()
setInterval()
2.setTimeout()
定时器 —–回调函数 callback
Window.settimeout (call function, delay time)
Window can omit the delay time is milliseconds
3. Stop setTimeout() timer clearTimeout()
4. The setInterval() timer invokes functions at intervals
5. Stop the setInterval() timer clearInterval()
6.this
- Global scope and ordinary functions
this
Point to window (inside the timerthis
Point to the window) - Who calls in a method call
this
Point to the who - In the constructor
this
Points to an instance of the constructor
4, JS execution queue (event loop)
1. Js is single-threaded
2. Synchronous (execution stack/main lane) and asynchronous (Task queue/emergency lane)
- Synchronization is executing one task at a time. Asynchrony is executing multiple tasks simultaneously
- Callback functions are asynchronous tasks
3. Js execution mechanism: A synchronous task is executed first, a callback function is encountered, and the task is put to the task queue. After the synchronous task is executed, the asynchronous task is executed
Location object
What is a Location object
The location property is used to get or set the FORM’s URL and to parse the URL —- returns an object
2. Url Unified Resource Locator
3. Location object properties
location.href
Gets or sets the entire URLlocation.search
Returns the parameter
4. Location.assign () redirection (retractable)
location.replace()
Replace current page (can’t go back)location.reload()
Reload the page if forced refresh (true); ctrl+f5
6. Navigator object
The commonly used attribute userAgent is used to determine whether a user opens the page on a PC or mobile
The history object
back()
backforward()
forwardThe go (parameters)
If the value is 1, one page is advanced. If the value is -1, one page is backward