Basic correlation between Web APIs and JS

  1. Composition of JS: JS syntax DOM BOM
  2. Web APIs: DOM BOM

API and Web apis

  1. API: Application programming interface, which is a set of predefined functions

    Simple understanding: is a tool to achieve the desired function

  2. 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

  1. Returns a collection of retrieved elements stored as a pseudo-array
  2. If there is only one LI in the page, it will return a pseudo-array
  3. 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

  1. Document.queryselector (' selector ')// Returns the first element object according to the specified selector
  2. Document. GetElementsByClassName (' the name of the class)// Returns a collection of element objects based on the class name
  3. Document. QuerySelectorAll (' selector ')// Returns a collection of all element objects for the specified selector

4. Get special elements (body, HTML)

  1. For the body:document.body
  2. 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

  1. element.innerText// The content from the start position to the end position, but it removes HTML tags as well as whitespace and newlines
  2. element.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:

  1. JS styles take the camel name fontSize backgroudColor
  2. The JS modification sytle style operation results in a high CSS weight for inline styles
  3. 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

  1. Get property values
  • Attributes element.
  • Element. The getAttribute (' property ')
  1. Setting property values
  • Element. attribute =' value '
  • Element.setattribute (' attribute ', 'value ')
  1. 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

  1. 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
  2. Gets H5 custom attributes

Element. getAttribute(‘ attribute ‘) H5 Add element.dataset. Index or element.dataset[‘index’]

Note:

  1. A dataset is a collection containing all the custom attributes starting with data
  2. If the custom attribute has more than one – join word take the hump nomenclatureconsole.log(div.dataset.listName)

5. Node operations

1. Why learn node operation: it is logical, but slightly less compatible

  1. Get elements using methods provided by the DOM
  2. Get elements using node hierarchies

In the DOM, nodes use node

  1. NodeType nodeType nodeName nodeName nodeValue nodeValue
  2. Element node 1 Attribute node 2 Text node 3
  3. The element node is the primary operation

3. Node hierarchy Father-son and elder brother hierarchy

  1. The parent node
  • node.parentNodeReturns the nearest parent of the element and returns null if no parent is found
  1. Child nodes
  • parentNode.childNodesYou get text nodes element nodes and so on
  • parentNode.childrenNonstandard is a read-only property that returns all child element nodes
  • parentNode.firstChildReturns the first node, either a text node or an element node
  • parentNode.lastChildReturns the last node whether it is a text node or an element node
  • parentNode.firstElementChildReturns the first child element
  • parentNode.lastElementChildReturns the last child element // and capricious problem above IE9 // written in actual development
  • console.log(ol.children[0])First child element
  • console.log(ol.children[ol.children.length - 1])The last child element

3. Sibling nodes

  • node.nextSiblingYou get the next sibling the text node the element node and so on
  • node.previousSiblingYou get the last sibling the text node the element node and so on
  • node.nextElementSiblingYou get the next sibling element node
  • node.previousElementSiblingThe result is the last sibling element node

4. Create a node

  • document.createElement('tagName')
  • Add a nodenode.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 ()

  1. If the parenthesis argument is empty or false, shallow copy copies only the tag and not the contents inside
  2. 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 redrawn
  • element.innerHTMLCreate 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)

  1. Traditional registration: with uniqueness, only one handler can be set for each element and event. The last registered handler overrides the previous one
  2. 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

  1. An event is an event object written inside the parentheses of our listening function as a parameter
  2. 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
  3. 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
  4. The event object can be named something else like Event, EVT, e
  5. Compatibility problem Internet Explorer 678 passeswindow.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 iee.srcElementGets the object that triggers the event
  • e.typeReturns the event object type
  • Prevents default actions (events) to prevent links from jumping or submit buttons from being submittede.preventDefault()
  • Lower version browsere.returnValue— Attributes or exploitsreturn falseIt 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

  1. e.stopPropagation(); / / standard
  2. 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

  1. Disable the right mouse button menu:contextmenu
  2. Disable mouse selection:selectstart

2. MouseEvent object: MouseEvent KeyboardEvent object: KeyboardEvent

  1. e.clientX/YReturns the x and y coordinates of the viewable area
  2. e.pageX/YReturns the x and y coordinates relative to the document page
  3. e.screenX/YIt returns the x and y coordinates relative to the computer screen
  4. mousemoveThe mouse moves
  5. mousedownThe mouse click
  6. mouseupRelease the mouse

Common keyboard events

  1. 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

  1. When the BOM browser object model interacts with the browser object
  2. 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

  1. window.onload=function(){}
  2. window.addEventListener('load',function(){})The most popular way to write it
  3. document.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

  1. window.onresize=function(){}
  2. window.addEventListerner('resize',function(){})
  3. window.innerWidthGets 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 functionsthisPoint to window (inside the timerthisPoint to the window)
  • Who calls in a method callthisPoint to the who
  • In the constructorthisPoints 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.hrefGets or sets the entire URL
  • location.searchReturns 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

  1. back()back
  2. forward()forward
  3. The go (parameters)If the value is 1, one page is advanced. If the value is -1, one page is backward