1. Introduction to Web APIs resume

The target

  • Be able to relate the Web APIs phase to the JavaScript syntax phase
  • Can you tell what an API is
  • Can you tell what a Web API is

Basic correlation between Web APIs and JS

Composition of JS: ECMAScript (JavaScript foundation), DOM (Page Document Object Model), BOM (Browser Object Model)

Web APIs include DOM and BOM

JS Basic stage

  • We are studying the basic syntax of the ECMAScript standard
  • Basic JS syntax is required
  • Basic syntax is not enough for common web interaction
  • The purpose is to lay the foundation and pave the way for the course behind JS

Web APIs phase

  • Web APIs are a w3c standard
  • Web APIs we just need to learn DOM and BOM
  • Web APIs are a unique part of our JS
  • We just need to learn about page interaction
  • Need to use JS based course content as the foundation

JS basic learning ECMAScript basic syntax for the future, Web APIs are JS applications, a lot of use of JS basic syntax for interactive effects.

API and Web apis

API

Apis (Application programming interfaces) are predefined functions designed to provide applications and developers with the ability to access a set of processes based on a piece of software or hardware without having to access the source code or understand the details of the inner workings.

Simple to understand: aN API provides a framework for programmers to more easily implement desired functionality.

Web API

Is a set of apis (BOM and DOM) provided by the browser for browser functionality and page elements

At this stage we mainly pop-up for the browser to explain the common API, mainly for the browser to do interactive effects.

For example, if we want the browser to pop up an alert box, use alert(‘ pop up ‘);

MDN detailed API: developer.mozilla.org/zh-CN/docs/…

Because there are so many Web APIs, we call this stage Web APIs

conclusion

  • An API is an interface for us programmers to implement something.
  • Web API is mainly for the interface provided by the browser, mainly for the browser to interact with the effect.
  • Web apis generally have inputs and outputs (parameters and return values of functions), and many Web apis are methods (functions).
  • Learning about Web apis can be done along the same lines as learning about built-in object methods.

2.DOM

The target

  • Can you tell what DOM is
  • Ability to get page elements
  • The ability to register events for elements
  • Ability to manipulate attributes of DOM elements
  • Being able to create elements
  • Ability to manipulate DOM nodes

Introduction of the DOM

Document Object Model is a standard programming interface recommended by W3C to handle extensible markup language (HTML or XML).

The W3C has developed a set of DOM interfaces that can change the content, structure, and style of web pages.

  • Document: A page is a document, represented in the DOM as document.
  • Element: All tags in a page are elements, represented by an element in the DOM.
  • Nodes: Everything in a web page is a node (tags, attributes, text, comments, and so on) and is represented in the DOM using Node.

DOM treats all of these things as objects.

Access to elements

How do I get page elements

DOM is primarily used to manipulate elements in our actual development

You can get elements in a page in one of the following ways:

  • Obtain by ID
  • Obtained by label name
  • Through HTML5 new methods to obtain
  • Special element fetch
(1) Obtain the value based on the ID

Get the element object with the ID using the getElementById() method.

<body> <div id="time">2021-9-5</div> <script> var timer = document.getElementById('time'); console.log(timer); <div id="time">2021-9-5</div> //console.dir (timer); </script> </body>Copy the code
(2) According to the label name

The getElementsByTagName() method returns a collection of objects with the specified label name.

The < body > < ul > < li > level 4 words 1 < / li > < li > level 4 words 2 < / li > < li > level 4 words 3 < / li > < li > level 4 words 4 < / li > < li > level 4 words 5 < / li > < / ul > < script > / / is returned Get over element object collection, stored in the form of pseudo array of var lists = document. The getElementsByTagName (" li "); console.log(lists); console.log(lists[0]); For (var I = 0; i < lists.length; i++){ console.log(lists[i]); } / / if the page is only one li, return an array or false / / if the page returned empty false without this element in the array in the form of var ul = document. The getElementsByTagName (" ul "); console.log(ul[0].getElementsByTagName('li')); </script> </body>Copy the code

You can also get all the children within an element (parent) with the specified tag name

Note: The parent element must be a single object (the element object must be specified), not the parent element itself.

(3) HTML5 new method acquisition
Document. GetElementsByClassName (' the name of the class '); // Returns a collection of element objects based on the class nameCopy the code
Document. querySelector(' selector '); // Returns the first element object according to the specified selectorCopy the code
Document. QuerySelectorAll (' selector '); // Returns a collection of all element objects for the specified selectorCopy the code

The instance

The < body > < div class = "box" > the box 1 < / div > < div class = "box" > box 2 < / div > < div id = "nav" > < ul > < li > home page < / li > < li > products < / li > < / ul > < / div > < script > / / 1. GetElemetnsByClassName according to the name of the class get some elements set var boxs = document. The getElementsByClassName (' box '); console.log(boxs); Var firstBox = document.querySelector('.box'); // Class selector console.log(firstBox); var nav = document.querySelector('#nav'); console.log(nav); var li = document.querySelector('li'); console.log(li); / / 3. QuerySelectorAll () returns all objects in the specified selectors var allBox = document. QuerySelectorAll (' box '); console.log(allBox); </script> </body>Copy the code
(4) Special element acquisition

1. Get the body element

2. Get the HTML element

Var bodyEle = document.body; console.log(bodyEle); console.dir(bodyEle); var htmlEle = document.documentElement; console.log(htmlEle); </script>Copy the code

Event based

The event concept

JavaScript gives us where to create dynamic pages, and events are behaviors that can be detected by JavaScript.

Simple understanding: trigger — response mechanism

Every element in a web page can generate some event that triggers JavaScript, for example, we can generate an event when a user clicks a button and then perform some action.

<body> <button id=" BTN "> </button> <script> (1) Event source: event triggered object var BTN = document.getelementById (' BTN '); // (2) Event type, how to trigger, what event. Btn. onclick = function() {alert(' chou-heong '); } </script> </body>Copy the code

Execute event procedure

1. Obtain the event source

2. Register events (bind events)

3. Add event handlers (in the form of function assignments)

<body> <div>123</div> <script> // 1. Var div = document.querySelector('div'); Div. Onclick // 3. Add event handler div.onclick = function() {console.log(' I'm selected '); } </script> </body>Copy the code

Operating elements

JavaScript DOM manipulation can change the content, structure and style of a web page. We can use DOM manipulation elements to change the content, attributes, etc. Note that the following are attributes.

Changing element content

(1) The content from the start position to the end position, but it removes HTML tags, and whitespace and newlines are also removed. Does not recognize HTML tags

element.innerText
Copy the code

(2) All content from the start position to the end position, including HTML tags, with Spaces and line breaks reserved

element.innerHTML
Copy the code

Instance of a

</div> <p>123</p> <script> // When we click the button, the text inside div will change // 1. Var BTN = document.querySelector('button'); var div = document.querySelector('div'); Btn.onclick = function() {//div. InnerText = '2021-09-06'; div.innerText = getDate(); } function getDate() { var date = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; var dates = date.getDate(); return year + '-' + month + '-' + dates; } var p = document.querySelector('p'); p.innerText = getDate(); </script> </body>Copy the code

InnerText is different from innerHTML

  • InnerText does not recognize HTML tags and is non-standard, removing whitespace and newlines.
  • InnerHTML identifies HTML tags and is a W3C standard, reserving whitespace and line breaks.

Both properties are read and written to get the contents of the element. InnerHTML is recommended.

Attribute operations for common elements

InnerText, innerHTML Changes the content of the element

2. SRC, href

3. Id, Alt, title

Case: Click the button to switch pictures

<body> <button id="anni"> </button></ button ID =" Anna "> </br> <img SRC =" anne.jpg "Alt ="" title=" Annie "> <script> // Change the element attribute SRC // 1. Var anni = document.getelementById ('anni'); var anna = document.getElementById('anna'); var img = document.querySelector('img'); Onclick = function() {img.src = 'anna.jpg '; // 2. Img. Title = 'Anna '; } anni.onclick = function() {img.src = 'anni.jpg '; Img. Title = 'Annie '; } </script> </body>Copy the code

Modifying form properties

Using the DOM, you can manipulate the following form element attributes:

Type, Value, Checked, selected, and disabledCopy the code

Example: Modify the value of a form

<body> <button> </button> <input type="text" value=" input content "> Var BTN = document.querySelector('button'); var input = document.querySelector('input'); Btn.onclick = function() {input.value = 'clicked '; // If a form needs to be disabled and can no longer be clicked, use disabled. We want the button to disable //btn.disabled = true; // This refers to the caller of the event function, in this case BTN this.disabled = true; } </script> </body>Copy the code

Case of imitation jingdong login page

Core ideas:

Click the eye button, change the password box type to text box can see the password inside.

A button has two states. Click once to switch to a text box, and click again to switch to a password box.

Algorithm: Use a flag variable to determine the value of flag. If it is 1, it switches to the text box and flag is set to 0. If it is 0, it switches to the password box and flag is set to 1.

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Word-wrap: break-word! Important; "> < p style>. width: 400px; border-bottom: 1px solid #ccc; margin: 100px auto; } .box input { width: 370px; height: 30px; border: 0; outline: none; } .box img { position: absolute; top: 5px; right: 2px; width: 24px; } < / style > < / head > < body > < div class = "box" > < label for = "" > < img SRC =" Annie. JPG "Alt =" "id =" eye "> < / label > < input type="password" name="" id="pwd"> </div> <script> // 1. Var eye = document.getelementById ('eye'); var pwd = document.getElementById('pwd'); Var flag = 0; Eye.onclick = function() {if(flag == 0){pwd.type = 'text'; Eye.src = 'anna.jpg '; flag = 1; }else { pwd.type = 'password'; Eye.src = 'anne.jpg '; flag = 0; } } </script> </body> </html>Copy the code

Style property operations

We can change the size, color, position and other styles of elements with JS

Element. className // className styleCopy the code

Note:

  • JS styles adopt camel naming, such as fontSize, backgroundColor
  • JS modify the style operation, resulting in inline style, CSS weight is relatively high
  • 1. If the style is modified more, you can change the element style by operating the class name.
  • Class is a reserved word, so use className to manipulate the element’s className attribute.
  • 3. ClassName changes the element’s className directly, overwriting the original className.

The instance

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta Name ="viewport" content="width=device-width, initial-scale=1.0"> <title> height: 200px; background-color: pink; } </style> </head> <body> <div></div> <script> // 1. Var div = document.querySelector('div'); / / 2. Register event, handler div. The onclick = function () {/ / div. The inside of the style attribute, use the hump nomenclature enclosing style. The backgroundColor = 'purple'; this.style.width = '250px'; } </script> </body> </html>Copy the code

Taobao click to close the TWO-DIMENSIONAL code case

Requirements: When the mouse click on the TWO-DIMENSIONAL code to close the button, then close the entire two-dimensional code

Display: None hides elements, display:block displays elements

Click the button to hide the QR code box.

The < body > < div class = "box" > taobao qr code < br / > < img SRC = "Annie. JPG" Alt = "" > < I class =" close - BTN "> x < / I > < / div > < script > / / 1. Var BTN = document.querySelector('.close-btn'); var box = document.querySelector('.box'); Btn.onclick = function() {box-style.display = 'none'; } </script> </body>Copy the code

Show hidden text box content case

Requirement: When the mouse clicks on the text box, the default text inside is hidden, when the mouse leaves the text box, the text inside is displayed.

Case analysis

First the form needs 2 new events, get focus onFocus lose focus onblur.

If you get focus, determine if the content in the form is the default text, and if so, clear the form.

<body> <input type="text" value=" mobile "> Var text = document.querySelector('input'); Onfocus text.onfocus = function() {if(this.value == 'phone '){text.value = ''; } console.log(' got focus '); Function () {if(this.value == ''){this.value = ''; } console.log(' lost focus '); } </script> </body>Copy the code

Modify the style property with className

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, "> < span style> < span style>. color: #fff; font-size: 25px; margin-top: 100px; } < / style > < / head > < body > < div class = "first" > text < / div > < script > / / 1. Var test = document.querySelector('div') if the style is small or if the function is simple; Test.onclick = function() {// Change the class name of our current element to change // 2. We can change the style of an element by modifying its className. This. ClassName = 'change'; //this. ClassName = 'first change'; //this. ClassName = 'first change'; } </script> </body> </html>Copy the code

Password box verification information example

If the entered number is not 6 to 16, an error message is displayed. If the entered number is not 6 to 16, a correct message is displayed.

Case Study:

  • The first thing to determine is that the form loses focus onblur
  • If the input is correct, the correct information will be displayed. The color is green and the small icon changes
  • If the input value is not 6 to 16, an error message is displayed
  • Because there are many changes in the style, we use className to modify the style
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta "> <title>Document</title> <style> div {width: 600px; margin: 100px auto; } .message { display: inline-block; font-size: 12px; color: #999; background: url(images/mess.png) no-repeat left center; padding-left: 20px; } .wrong { color: red; background-image: url(images/wrong.png); } .right { color: green; background-image: url(images/right.png); } </style> </head> <body> <div class="register"> <input type="password" class="ipt"> <p class="message"> </div> <script> // 1. Var ipt = document.querySelector('.ipt'); var message = document.querySelector('.message'); Ipt. Onblur = function(){ Ipt. Value. Length if (this. Value. Length < 6 | | this. Value. The length > 16) {/ / console log (' error message. The className = 'message wrong'; Message. innerHTML = 'The number of digits you entered is incorrect. }else { message.className = 'message right'; Message. innerHTML = 'You typed it correctly '; } } </script> </body> </html>Copy the code

summary

The operation element is the core of the DOM

  • Manipulate element contents: innerText, innerHTML
  • Manipulate common element attributes: SRC, href, title, Alt, and so on
  • Manipulate form attributes: Type, Value, disabled, etc
  • Manipulate element style attributes: element.style, className

Exclusive ideas

If we have the same set of elements and we want one element to implement a certain style, we want to use the exclusive-minded algorithm of the loop:

1. Clear styles for all elements

2. Style the current element

3, pay attention to the order can not be reversed, first kill others, then set yourself

Example: Multiple buttons, click on the button, the button turns pink

<body> <button> button 1</button> <button> button 2</button> <button> button 3</button> </button> <button> button 5</button> <script> / / 1. Obtain all button element var BTNS = document. GetElementsByTagName (" button "); BTNS [I] for(var I = 0; i < btns.length; i++){ btns[i].onclick = function() { // 1. For (var I = 0; i<btns.length; i++){ btns[i].style.backgroundColor = ''; } / / 2. Then let the current element background color for the pink 1 enclosing style. The backgroundColor = 'pink'; } } </script> </body>Copy the code

Baidu skin change effect

Case: Click on the image to change the background image

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta "> <title>Document</title> <style> * {margin: 0; padding: 0; } body { background: url(images/1.jpg) no-repeat center top; } li { list-style: none; } .baidu { overflow: hidden; margin: 100px auto; background-color: #fff; width: 410px; padding-top: 3px; } .baidu li { float: left; margin: 0 1px; cursor: pointer; } .baidu img { width: 100px; } </style> </head> <body> <ul class="baidu"> <li><img src="images/1.jpg"></li> <li><img src="images/2.jpg"></li> <li><img src="images/3.jpg"></li> <li><img src="images/4.jpg"></li> </ul> <script> // 1. Var imgs = document.querySelector('.baidu').querySelectorAll('img'); For (var I = 0; i < imgs.length; i++){ imgs[i].onclick = function() { document.body.style.backgroundImage = 'url(' + this.src + ')'; } } </script> </body> </html>Copy the code

Table interlaced color effect

Case Study:

Using the new mouse event over onMouseOver, the mouse leaves onMouseOut.

Mouse result tr line, current row change tragedy color, mouse away remove current background color.

Note: The first line (the line inside thead) does not need to change color, so we get the line inside tBody.

Example:

Var TRS = document.querySelector(' tBody ').querySelectorAll('tr'); For (var I = 0; i < trs.length; TRS [I].onmouseover = function() {//console.log(' mouseover '); this.className = 'bg'; TRS [I]. Onmouseout = function() {this.className = ""; } } </script>Copy the code

Form Select All Cancel select all case

Case Study:

1, select all and deselect all: let the checked properties of all the following check boxes (checked state) follow the select button.

2, the following check boxes need to be all selected, all above can be selected practice: bind click events to all the following check boxes, each click, to cycle to check whether all the following check boxes are not selected, if there is one not selected, all above is not selected.

<script> // 1. Select all and deselect all: Let the checked properties of all the following check boxes follow the select all button. Var j_cbAll = document.getelementById ('j_cbAll'); Var j_tbs = document.getelementById ('j_tb').getelementsByTagName ('input'); J_cball.onclick = function() {// this.checked checks the status of the current check box. If false, console.log(this.checked) is unchecked; for(var i = 0; i < j_tbs.length; i++){ j_tbs[i].checked = this.checked; For (var I = 0; var I = 0; i < j_tbs.length; I ++){j_tbs[I].onclick = function() {var flag = true; Var j = 0; j < j_tbs.length; j++){ if(! j_tbs[j].checked){ flag = false; break; } } j_cbAll.checked = flag; } } </script>Copy the code

Actions for custom properties

1. Obtain the attribute value

  • Element. property: Gets the value of the property
  • Element. GetAtribute (‘ property ‘); // Good compatibility

The difference between:

  • Element. attribute: Gets the value of the built-in attribute (the element’s own attribute)
  • Element.getattribute (‘ attribute ‘); Mainly get custom properties (standard), we programmers custom properties

The instance

<body>
    <div id="demo" index="1" jack="make"></div>
    <script>
        var div = document.querySelector('div');
        // 1. 获取元素的属性
        // (1) element.属性
        console.log(div.id);
        // (2) element.getAttribute('属性'),get得到获取 attribute 属性的意思
        // 我们程序员自己添加的属性,我们称为自定义属性 index
        console.log(div.getAttribute('id'));
        console.log(div.getAttribute('index'));
        console.log(div.getAttribute('jack'));      //自定义属性
    </script>
</body>
Copy the code

2. Set to remove user-defined attributes

(1) Set the element attribute value

element.setAttribute()
Copy the code

Add to the above

// (1) element. attribute = 'value' div. Id = 'test'; div.className = 'navs'; // (2) element.setAttribute(' attribute ', 'value '); SetAttribute ('index', 2); div.setAttribute('class', 'footer');Copy the code

(2) Remove attributes

The removeAttribute (property)Copy the code

TAB column switching case

Requirements: When the mouse clicks on the corresponding TAB above (TAB), the following content follows the change

Case analysis

1, Tab bar switch from 2 large modules

2, above the module TAB, click on a, the current background color will be red, the rest of the same (exclusivity), change the way the class name

3. The contents of the following modules will change with the tabs above. So the following module changes are written to the click event.

4. Rule: The following module displays a one-to-one correspondence with the above tabs.

Add a custom attribute (index) to all li’s in tab_list. The attribute values are numbered from 0.

6. When we click on a li in tab_list, let the tab_con contents show the corresponding sequence number, and hide the rest (exclusivity).

Var tab_list = document.querySelector('.tab_list'); var tab_list = document.querySelector('. var lis = tab_list.querySelectorAll('li'); var items = document.querySelectorAll('.item'); For (var I = 0; i < lis.length; Lis [I].setAttribute('index', I); lis[I].setAttribute('index', I); Lis [I]. Onclick = function() {var I = 0; i < lis.length; i++){ lis[i].className = ''; } // leave myself this.className = 'current'; Var index = this.getAttribute('index'); console.log(index); For (var I = 0; i < items.length; i++){ items[i].style.display = 'none'; } items[index].style.display = 'block'; } } </script>Copy the code

H5 Custom attributes

The purpose of custom attributes is to save and use data. Some data can be saved in a page rather than in a database.

Custom attributes are obtained using getAttribute(‘ attributes ‘).

However, some custom attributes are very ambiguous, and it is not easy to determine whether they are original built-in attributes or custom attributes.

H5 gives us new custom attributes;

(1) Set H5 custom attributes

H5 specifies the custom property data- beginning as the property name and assigns a value.

For example, <div data-index="1"></div> or div.setattribute ('data-time', 20);Copy the code

(2) Obtain H5 custom attributes

1. Get element.getattribute ('data-index') for compatibility. // dataset is aset of fields that contain all the custom fields starting with data. H5 adds element.dataset. Index or element.dataset.['index'], IE 11 only supports this.Copy the code

Node operation

Why learn node operations?

The main purpose is to get elements.

1. Get elements using methods provided by DOM

document.getElementById()
document.getElementByTagname()
document.querySelector()
Copy the code

Faults: weak logic, cumbersome.

2. Use node hierarchy to obtain elements

  • Elements are obtained by using the father-son and brother-son node relationships
  • More logical, easier to use, but less compatible

Summary of the node

Everything in a web page is a node (tag, attribute, text, comment, etc.), and in the DOM, nodes are represented using Node.

All nodes in the HTML DOM tree are accessible through JavaScript, and all HTML elements (nodes) can be modified, created or deleted.

Typically, a node has at least three basic attributes: nodeType (nodeType), nodeName (nodeName), and nodeValue (nodeValue).

  • The element node nodeType is 1
  • Attribute node nodeType is 2
  • The text node nodeType is 3 (the text node contains text, Spaces, line feeds, and so on)

In real development, node operations operate primarily on element nodes

Node level

DOM tree can be used to divide nodes into different hierarchical relationships, the common one is the parent-child hierarchical relationship.

The parent node

Returns the nearest parent of the element, or null if no parent is found

< div class = "demo" > < div class = "box" > < span class = "erweima" > x < / span > < / div > < / div > < script > / / 1. ParentNode var erweima = document.querySelector('.erweima'); Return null console.log(erweima.parentnode) if the parentNode is not found; </script>Copy the code
Child nodes

(standard)

ParentNode..childnodes (standard)Copy the code

Parentnode. childNodes returns an updated collection of children of the specified node.

  • Note: The return value contains all child nodes, including element nodes, text nodes, and so on.
  • If you only want to get inside element nodes, you need to do this. So childNodes is generally not recommended.
<ol> <li> I am li 1</li> <li> I am Li 2</li> <li> I am li 3</li> </li> <script> var ul = document.querySelector('ul'); // 1. ChildNodes, childNodes all childNodes contain element nodes, text nodes, and so on console.log(ul.childnodes); console.log(ul.childNodes[0].nodeType); FirstElementChild returns the first child node console.log(ol.firstelementChild); console.log(ol.lastElementChild); Console. log(ol.children[0]); // Children [0]; console.log(ol.children[ol.children.length-1]); </script>Copy the code

(2) Non-standard

Parentnode. children(non-standard)Copy the code

Parentnode. children is a read-only property that returns all 1-child element nodes (element nodes). It returns only the child source node, not the other nodes.

Although children is not standard, it is supported by all browsers, so we can use it safely.

The first and last child elements

FirstChile, lastChild

parentNode.firstChild
Copy the code

FirstChild returns the firstChild, or null if not found. Again, a node that contains all 1s

parseNode.lastChild
Copy the code

FirstElementChild, lastElementChild

/ / firstElementChild returns the first child node, and can't find it returns null parentNode. FirstElementChild / / lastElementChild returns the last child node, Can't find it returns null parentNode lastElementChildCopy the code

Note: these two methods have compatibility issues, IE 9 and later only support.

In practice, firstChild and lastChild contain other nodes, which is inconvenient. FirstElementChild and lastElementChild have compatibility issues. How do we get the first and lastChild nodes?

Console. log(ol.children[0]); // Children [0]; console.log(ol.children[ol.children.length-1]);Copy the code
Sina dropdown menu

After the mouse, the drop-down menu appears

Case Study:

Li in the navigation bar should have mouse results, so need to register mouse events cycle;

Core principle: When the mouse passes over the second child in Li, UL shows, when the mouse leaves, UL hides.

Var nav = document.querySelector('.nav'); var lis = nav.children; For (var I = 0; i < lis.length; Lis [I].onmouseover = function() {this.children[1].display = 'block'; } lis[i].onmouseout = function() { this.children[1].style.display = 'none'; } } </script>Copy the code
Brother nodes
1, node. NextSiblingCopy the code

NextSibling returns the nextSibling of the current element, or null if it cannot be found. Again, it contains all nodes.

2, node. PreviousSiblingCopy the code

PreviousSibling returns a sibling on the current element, null if none is found, and also includes all nodes.

Node.nextelementsibling //Copy the code

NextElementSibling Returns the next sibling of the current element, or null if it cannot be found.

4, node. PreviousElementSibling / / have compatibility problems, ie 9 or more supportCopy the code

PreviousElementSibling Returns a sibling on the current element, or null if it cannot be found.

How to resolve compatibility issues?

A: Invert a compatibility function yourself

Function getNextElementSibling(element) {var el = element; While (el = el.sibling){// if(el.nodeType === 1){return el; } } return null; }Copy the code
Create and add nodes

(1) Create a node

document.createElement('tagName')
Copy the code

The document.createElement() method creates the HTML element specified by tagName. Because these elements do not originally exist and are dynamically generated based on our requirements (such as comment sections), we also call them dynamically created element nodes.

(2) Add a node

node.appendChild(child)
Copy the code

The node.appendChild() method adds a node to the end of the list of children of the specified parent node. Similar to the after pseudo-element in CSS.

The instance

<body> <ul> <li>123</li> <li>456</li> </ul> <script> // 1. Var li = document.createElement('li'); Node.appendchild (child); node.appendChild(child); push var ul = document.querySelector('ul'); ul.appendChild(li); // 3. Add node node.insertbefore (child, specify element); var lili = document.createElement('li'); ul.insertBefore(lili, ul.children[1]); </script> </body> we want to add a new element to the page.Copy the code
Simple version release message case

Case analysis

After clicking the button, dynamically create a LI and add it to ul.

When you create li, assign the value of the text field to Li using li.innerhtml.

AppendChild is used if you want the new message to follow, insertBefore is used if you want the message to follow

Code implementation

The < body > < textarea name = "" id =" "> < / textarea > < button > publish < / button > < ul > < / ul > < script > / / 1. Var BTN = document.querySelector('button'); var text = document.querySelector('textarea'); var ul = document.querySelector('ul'); Btn.onclick = function() {if(text.value == "){alert(' you did not enter anything '); }else { console.log(text.value); Var li = document.createElement('li'); li.innerHTML = text.value; // appendChild(li); InsertBefore (li, ul.children[0]); } } </script> </body>Copy the code
Remove nodes
node.removeChild(child)
Copy the code

The node.removechild () method removes a child node from the DOM and returns the deleted node.

Example:

The < body > < button > delete < / button > < ul > < li > bear big < / li > < li > bears two < / li > < li > baldheaded stronger < / li > < / ul > < script > / / 1. Get the element var ul = document.querySelector('ul'); var btn = document.querySelector('button'); Node.removechild (child) // ul.removechild (ul.children[0]); Btn. onclick = function() {if(ul.children. Length >= 1){ul.children[0]); } if(ul.children.length == 0){// If there is no node, the button becomes gray this.disabled = true; } } </script> </body>Copy the code
Deleting messages

Case analysis

When we copy the value of the text field to Li, we add a delete link.

We need to get all the links, when we click the current link, delete the current link li;

To prevent a connection jump, add javascript:void(0); Or javascript:;

Implementation: On the basis of the above simple version of the release message case, add code

<script> // 1. Get the element var BTN = document.querySelector('button'); var text = document.querySelector('textarea'); var ul = document.querySelector('ul'); Btn.onclick = function() {if(text.value == "){alert(' you did not enter anything '); return false; }else { console.log(text.value); Var li = document.createElement('li'); // javascript:; Li.innerhtml = text.value + '<a href="javascript:;" > delete < / a > '; // appendChild(li); InsertBefore (li, ul.children[0]); / / (3) remove elements, delete the current connection li it as the father of var = document. QuerySelectorAll (' a '); for(var i = 0; i < as.length; i++){ as[i].onclick = function() { // node.removeChild(child); RemoveChild (this.parentNode); // Delete li ul.removeChild(this.parentNode); } } } } </script>Copy the code
Replication node (clone node)
node.cloneNode()
Copy the code

The node.clonenode () method returns a copy of the node on which it was called. Also known as clone node/copy node.

Use the sample

<body> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> <script> var ul = document.querySelector('ul'); // 1. node.cloneNode(); // 2. Node. cloneNode(true); Var lili = ul.children[0]. CloneNode (true); // clone 1 ul.appendChild(lili); </script> </body>Copy the code

Note:

1. If the parentheses are empty or not false, the shallow copy is cloned, that is, only the replicated node itself is cloned, not the children inside the cloned node.

2. If the parenthesis argument is true, it is a deep copy, complicating the node itself and all its children

Use the sample

<body> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> <script> var ul = document.querySelector('ul'); // 1. node.cloneNode(); // 2. Node. cloneNode(true); Var lili = ul.children[0]. CloneNode (true); // clone 1 ul.appendChild(lili); </script> </body>Copy the code

Note:

1. If the parentheses are empty or not false, the shallow copy is cloned, that is, only the replicated node itself is cloned, not the children inside the cloned node.

2. If the parenthesis argument is true, it is a deep copy, complicating the node itself and all its children

Dynamically generated tables

Case Study:

1, because the student data inside is dynamic, we need JS dynamic generation, here we simulate the data, define the data. We store data dynamically;

2. All data is placed in the line inside the body;

3. Because there are many rows, we need to loop to create multiple rows (corresponding to how many people);

4. Each row has many cells (corresponding to the data in it), and we continue to use loops to create multiple cells and store data in them (double for loop);

5, the last column of cells is deleted, need to create a separate cell.

The main code

The < body > < table cellspacing = "0" > < thead > < tr > < th > name < / th > < th > account < / th > < th > results < / th > < th > action < / th > < / tr > < thead > < tbody > </tbody> </table> <script> // 1. Var datas = [{name: 'wei Yingluo ', subject: 'JavaScript', score: 100}, {name:' wei Yingluo ', subject: 'Score ',} 'JavaScript', score: 98}, {name: 'JavaScript', Score: 99}, {name: 'Ming yu ', subject: 'JavaScript', score: 88}, {name: 'JavaScript', subject: 'score ', 0}]; Var tBody = document.querySelector(' tBody '); for(var i = 0; i < datas.length; Var tr = document.createElement('tr'); tbody.appendChild(tr); // create a cell in the row (3 cells related to the data). Data [I] for(var k in datas[I]) {var td = var td = var td = var td = var td = var td = var td = var td = var td = document.createElement('td'); Datas [I][k] = td //console.log(datas[I][k]); td.innerHTML = datas[i][k]; tr.appendChild(td); Var td = document.createElement('td'); td.innerHTML = '<a href="javascript:;" > delete < / a > '; tr.appendChild(td); } / / 4. Delete operation began to var as = document. QuerySelectorAll (' a '); for(var i = 0; i < as.length; I ++){as[I].onclick = function() {node.removechild (child) tbody.removeChild(this.parentNode.parentNode); }} /* for(var k in obj){obj[k] = obj} */ </script> </body>Copy the code

Three dynamically created element differences

  • document.writ()
  • element.innerHTML
  • document.createElement()

The difference between

Document. write is a content flow that writes content directly to the page, but when the document flow is complete, it causes the page to be completely redrawn.

InnerHTML writes content to a DOM node without causing the page to be completely redrawn.

InnerHTML creates multiple elements more efficiently (instead of concatenating strings, concatenate them as arrays), with a slightly more complex structure.

CreateElement () creates multiple elements slightly less efficiently, but with a clearer structure.

Summary: innerHTML is more efficient than createElement in different browsers

The DOM core

Document Object Model (DOM) is a standard programming interface recommended by W3C to handle extensible markup language (HTML or XML).

The W3C has defined a set of DOM interfaces that allow you to change the content, structure, and style of a web page.

1. For JavaScript, in order to enable JavaScript to manipulate HTML, JavaScript has its own DOM programming interface.

2. In the case of HTML, DOM makes HTML a DOM tree containing documents, elements, and nodes.

The DOM element we get is an object, so it is called the Document Object Model.

With respect to DOM manipulation, we focus on manipulation of elements. There are mainly create, add, delete, change, check, attribute operation, event operation.

create

1. document.write
2. innerHTML
3. createElement
Copy the code

increase

1. appendChild
2. insertBefore
Copy the code

delete

1. removeChild
Copy the code

change

Mainly modify dom element attributes, CONTENT and attributes of DOM elements, form values, etc. 1. Alter element attributes: SRC, href, title 2. Alter element contents: innerHTML, innerText 3. Modify form elements such as value, Type, and disabled. 4. Modify the element styles: style, classNameCopy the code

check

GetElementById; getElementsByTagName; getElementById; getElementsByTagName; QuerySelector, querySelectorAll advocate 3. Use node operation to obtain elements: parentNode, children, previousElementSibling, nextElementSibling, advocateCopy the code

Attribute operation

This applies primarily to custom attributes

SetAttribute: sets the DOM attribute value. GetAttribute: obtains the DOM attribute value. 3Copy the code

Event operations

Register an event for the element, taking the event source. Event type = event handler

Mouse events The trigger condition
onclick Click the left mouse button trigger
onmouseover Mouse result trigger
onmouseout Mouse away trigger
onfocus Get mouse focus trigger
onblur Lost mouse focus trigger
onmousemove Mouse movement trigger
onmouseup The mouse clicks
onmousedown Mouse press trigger

The event, a senior

The target

  • There are two ways to write an element registration event
  • Name two ways to delete events
  • Be able to name three stages of the DOM event flow
  • Ability to follow mouse cases using event objects
  • Encapsulates compatibility functions that prevent bubbling
  • Be able to explain the principle of event delegation
  • Ability to output common mouse and keyboard events

Register events (bind events)

Adding events to an element is called a registration event or a binding event.

There are two types of registration events: traditional and method listening registration.

Traditional Registration
Onclick <button onclick = "alert('hi ')"></button> btn.onclick = function() {} Only one handler can be set at a time. The last handler registered will override the previous oneCopy the code
Method listens for the registration mode
  • W3C standard, recommended
  • AddEventListener () is a method
  • Internet Explorer prior to Internet Explorer 9 does not support this method. Instead, use attachEvent()
AddEventListener Event listening mode
eventTarget.addEventListener(type, listener [, userCapture])
Copy the code

EventTarget. AddEventListener () method specifies the listeners registered to the eventTarget (target), when the object trigger event is specified, the event handler should be executed.

This method takes three arguments:

  • Type: String of event types, such as click and mouseover, without on
  • Listener: an event handler that is called when an event occurs
  • UseCapture: Optional, a Boolean value, false by default. Once you’re done with the DOM event flow, go further.
AttachEvent Mode for listening to events
eventTarget.attachEvent(eventNameWithOn, callback)
Copy the code

The eventTarget.attachevent () method registers the specified listener to the eventTarget(the target object), and when that object fires the specified event, the specified callback function is executed.

This method takes two arguments:

EventNameWithOn: String of event type, such as onclick, onmouseOver, with ON

Callback: event handler that is called when the target triggers an event.

The instance
</button> <button> < IE9 attachEvent</button> <script> var BTNS = document.querySelectorAll('button'); BTNS [0]. Onclick = function() {alert('hi'); } BTNS [0]. Onclick = function() { AddEventListener // (1) the event type is a string, must be quoted, and does not have on // (2) the same element, BTNS [1]. AddEventListener ('click', function() {alert(22); }) btns[1].addEventListener('click', function() { alert(33); }) // 3. AttachEvent ('onclick', function() {alert(44); }) </script> </body>Copy the code

Delete event (unbind event)

How to delete an event

1. Traditional registration

eventTarget.onclick = null;
Copy the code

Method listens for the registration mode

eventTarget.removeEventListener(type, listener[, useCapture]);
Copy the code
Delete the event compatibility solution
function removeEventListener(element, eventName, Fn) {/ / whether the current browser support if removeEventListener method (well. RemoveEventListener) {element. The removeEventListener (eventName, fn); } else if(element.detachEvent) { element.detachEvent('on' + eventName, fn); } else { element['on' + eventName] = null; }}Copy the code

The DOM event flow

The theory of

The event flow describes the order in which events are received from the page.

Events are propagated from node to node in a specific order as they occur, and this propagation process is called DOM event flow.

Let’s say we register a click event for a div:

The DOM event flow is divided into three phases:

  • Capture phase
  • Current target stage
  • Bubbling phase

Event bubbling: A process first proposed by IE in which an event is initially received by the most specific element and then propagated up the hierarchy to the topmost node of the DOM.

Event capture: First described by Netscape, the process of starting at the topmost node of the DOM and propagating down the hierarchy to the most specific element received.

DOM event flow code validation

Pay attention to

2. Onclick and attachEvent can only get the bubbling phase. 3. AddEventListener (type, listener[, useCapture]) the third parameter, if true, indicates that the event handler is invoked during the event capture phase. If false (the default is false if you do not write), the event handler is invoked during the event bubble phase. 4. We rarely use event capture in actual development, focusing more on event bubbling. Some events do not bubble, such as onblur, onfocus, onMouseEnter, onmouseleave 6. Event bubbling can sometimes cause trouble, and sometimes it can help to do something very cleverlyCopy the code

The sample

<div class="father"> <div class="son">son box </div> </div> <script> // dom events flow in three stages // 1. Onclick and addEventListener, if the third parameter is true, are in capture phase // 3. // Document -> HTML -> body -> father -> son Son var son = document.querySelector('.son'); son.addEventListener('click', function() { alert('son'); }, true); var father = document.querySelector('.father'); father.addEventListener('click', function() { alert('father'); }, true); // son -> father -> body -> HTML -> document // son -> father -> body -> document Father var son = document.querySelector('.son'); son.addEventListener('click', function() { alert('son'); }, false); var father = document.querySelector('.father'); father.addEventListener('click', function() { alert('father'); }, false); / / bubbling phase, document the popup document. AddEventListener (' click ', function () {alert (' document '); }); </script>Copy the code

The event object

1. What are event objects
EventTarget. Onclick = function (event) {} eventTarget. AddEventListener (' click ', function (event) {}) / / this event is the event object, You can customize, such as E and EVTCopy the code
  • The event object represents the state of the event, such as the state of the keyboard key, the position of the mouse, and the state of the mouse button.
  • Simple understanding: After an event occurs, the collection of information data related to the event is put into this object. This object is the event object, which has many attributes and methods.

Such as:

1. Who binds this event.

2. When the mouse triggers an event, it will get information about the mouse, such as the mouse position.

2. Event object usage syntax
Eventtarget.onclick = function(event) {eventTarget.onclick = function(event) { E, evt etc} eventTarget. AddEventListener (' click ', function (event)) {/ / this event is the event object, can be customized, such as: e, evt etc}Copy the code

The event is a parameter. The system sets it as an event object for us, without passing an argument.

When we register an event, the event object is automatically created by the system and passed in turn to the event listener (event handler).

3. Compatibility scheme of event objects

The event object itself has compatibility issues:

1. In standard browsers, the parameters passed by the browser to the method can be obtained by defining parameter E.

2. In IE 6~8, the browser does not pass parameters to methods. If necessary, the method must be retrieved from window.event.

Solution:

e = e || window.event;
Copy the code

The sample

<body> <div>123</div> <script> // var div = document.querySelector('div'); // div.onclick = function(event) { // console.log(event); // console.log(window.event); / / compatible ie678 / / e = e | | window. The event / /} div. AddEventListener (' click ', function (e) {the console. The log (e); }) // 1. Event is an event object written inside the parentheses of our listener function. The event object will exist only when there is an event. It is automatically created by the system for us, and we do not need to pass parameters. The event object is a set of data related to our event. The information related to the event, such as the mouse click, contains the information related to the mouse, mouse coordinates, if it is a keyboard event, contains the information about the keyboard event, for example, determine which key the user pressed // 4. We can name the event object ourselves, such as event, EVT, e, etc. // 5. Windows. Event </script> </body>Copy the code
4. Common attributes and methods
Event object property method instructions
e.target Return the object that triggered the event (standard)
e.srcElement Returns the object that triggered the event (non-standard, used by IE6 ~8)
e.type Returns the type of trigger event, such as click, mouseover, without on
e.cancelBubble This property prevents bubbling, non-standard, and used by IE6 ~8
e.returnValue This property prevents default events (default behavior) that are not standard and used by IE6 ~8, such as not allowing links to jump
e.preventDefault() This method blocks default events (default behavior), standards, such as not allowing links to jump
e.stopPropagation() Prevent bubbling, standard

The sample

The < body > < div > 123 < / div > < ul > < li > abc1 < / li > < li > revised < / li > < li > abc3 < / li > < / ul > < script > / / common properties and methods of the event object / / 1. E. arget This returns the object (element) that triggered the event, this returns the object (element) bound to who loves you most // Difference: e.target returns the element clicked, this: Var div = document.querySelector('div'); div.addEventListener('click', function(e){ console.log(e.target); console.log(this); }); var ul = document.querySelector('ul'); Ul.addeventlistener ('click', function(e) {ul console.log(this); ul console.log(this); // e.target points to the object we clicked on, who triggered the event, we clicked on Li, e.target points to Li console.log(e.target)}); / / understanding / * compatibility div. The onclick = function () {e = e | | window. The event; var target = e.target || e.srcElement; console.log(target); </script> </body> </script> </body>Copy the code

Blocking default behavior

</div> <a href="http://www.baidu.com"> </a> <form action="http://www.baidu.com"> <input type="submit" Value =" submit "name="sub"> </form> <script> Return the event type var div = document.querySelector('div'); div.addEventListener('click', fn); div.addEventListener('mouseover', fn); Div. AddEventListener ('mouseout', fn); Function fn(e) {console.log(e.type); Var a = document.querySelector('a'); A.addeventlistener ('click', function(e) {e.preventDefault(); A.onclick = function(e) {// e.preventDefault() e.preventdefault (); // Lower version Internet Explorer 678, returnValue property e.returnValue; // We can use return false to block the default behavior. There are no compatibility issues. alert(11); } </script> </body>Copy the code

Prevents events from bubbling

concept

Event bubbling: It is initially received by the most concrete element and propagated up the hierarchy to the topmost node of the DOM.

The characteristics of event bubbling itself, will bring harm, will also bring benefits, we need to flexibly grasp.

Two ways to prevent events from bubbling

Standard: Use the stoopPropagation() method in event objects. Internet Explorer 6 to 8 is incompatible

e.stopPropagation()
Copy the code

Non-standard: IE 6 to 8 uses the event object cancelBubble property

Compatibility Solution
if (e && e.stopPropagation) {
    e.stopPropagation();
} else {
    window.event.cancelBubble = true;
}
Copy the code
The instance
<body> <div class="father"> <div class="son">son </div> </div> <script> // Common event object properties and methods // prevent bubbling dom recommended standard stopPropagation() var son = document.querySelector('.son'); son.addEventListener('click', function(e) { alert('son'); e.stopPropagation(); Propagation e. canelble = true; // nonstandard, cancel cancel, bubble bubble}, false); var father = document.querySelector('.father'); father.addEventListener('click', function() { alert('father'); }, false); document.addEventListener('click', function() { alert('document'); }) </script> </body>Copy the code

Event delegate (proxy, delegate)

For example,

The characteristics of event bubbling itself, will bring harm, will also bring benefits, we need to flexibly grasp, there are the following scenarios in life:

There are 100 students in the class and 100 couriers. If it takes a long time to deliver one by one, and each student needs to queue up to get it, what should I do?

Solution: The Courier entrusted 100 packages to the homeroom teacher. The homeroom teacher put the packages in the office and the students could get them by themselves after class.

Advantage: Courier save trouble, entrusted to the class teacher can go. The students also get convenient, because I believe in the teacher.

The application also has a scenario like this:

<ul> <li> Know you know, I should have a frame in hand! </li> <li> </li> </li> <li> </li> </li> <li> </li> </li> <li> </li> </li> </ul>Copy the code

Clicking on each LI will bring up a dialog box. Previously, registering events for each LI would have been laborious, and accessing the DOM more often would have delayed the interaction ready time of the entire page.

Event delegate is also called event delegate, or event delegate in jQuery.

The principle of event delegation

Instead of scheduling event listeners for each child node, event listeners are set on its parent node and then influenced to set each child node using the bubbling principle.

The role of event delegation

We only manipulate the DOM once, which improves the performance of the program.

The instance
<body> <ul> <li> </li> <li> </li> </li> <li> </li> </li> <li> </li> </li> <li> </li> </li> </ul> <script> </li> </ul> </ul> Ul.addeventlistener ('click', function(e) {// alert(' alert '); '); / / e. arget this can get us click on the object of e. arget. Style. The backgroundColor = 'pink'; }) </script> </body>Copy the code

Common mouse events

Mouse Events Summary

Mouse events The trigger condition
onclick Click the left mouse button trigger
onmouseover Mouse over trigger
onmouseout Mouse away trigger
onfocus Get mouse focus trigger
onblur Lost mouse focus trigger
onmousemove Mouse movement trigger
onmouseup The mouse clicks
onmousedown Mouse press trigger
Disable text selection and right-click menus

1. Forbid the right mouse button menu

Contextmenu controls when the contextmenu should be displayed and is used by programmers to disable the default contextmenu

document.addEventListener('contextmenu', function(e)) {
    e.preventDefault();
}
Copy the code

2. Disable mouse selection (selectStart)

document.addEventListener('selectstart', function(e)) {
    e.preventDefault;
}
Copy the code

The instance

The < body > I am not willing to share paragraphs < script > / / 1. Document contextmenu can disable right click menu. AddEventListener (' contextmenu ', function(e) { e.preventDefault(); }); / / 2. The ban on selected text selectstart document. The addEventListener (' selectstart ', function (e) {e.p reventDefault (); }); </script> </body>Copy the code
Gets the coordinates of the mouse on the page

An event object represents the state of an event, a collection of information related to the event. At this stage we are mainly using the mouse to event objects

MouseEvent and KeyboardEvent object KeyboardEvent

Mouse event object instructions
e.clientX Return mouse relative toBrowser window visualization areaThe X coordinate
e.clientY Returns the Y coordinate of the mouse relative to the browser window visualization area
e.pageX Returns the x-coordinate of the mouse relative to the document page, supported by IE9+
e.pageY Returns the y-coordinate of the mouse relative to the document page, supported by IE9+
e.screenX Returns the x-coordinate of the mouse relative to the computer screen
e.screenY Returns the Y coordinate of the mouse relative to the computer screen

The instance

<head> <style> body { height: 3000px; } < / style > < / head > < body > < script > / / mouse event object MouseEvent document. The addEventListener (' click ', Function (e) {console.log(e.clientx); function(e) {// 1. console.log(e.clientY); console.log('------------------------'); // 2. Page mouse over the x and y coordinates of the page document console.log(e.pagex); console.log(e.pageY); }) </script> </body>Copy the code
Follow the mouse moving angel

Example: This angel picture keeps moving with the mouse

Case analysis

1, the mouse continues to move, using the mouse to move the event: Mousemove

2. Move around the page and register the event for Document

3, the picture to move for example, and do not occupy the position, we can use the function of absolute positioning

The instance

<head> <style> img { position: absolute; /* absolute position */ top: 2px; width: 50px; height: 50px; } </style> </head> <body> <img src="images/angel.gif" alt=""> <script> var pic = document.querySelector('img'); Document. AddEventListener (' mousemove ', function (e) {/ / 1. Mousemove mouse 1 px, as long as we can trigger the event / / console log (1) / 2. Var x = e.pagex; var x = e.pagex; var x = e.pagex; var y = e.pageY; Console. log('x is: '+x, 'y is: '+y); Pic. style. Left = x-20 + 'px'; pic.style.top = y - 20 + 'px'; }) </script> </body>Copy the code

Common keyboard events

Triggering event

Events can be triggered using a keyboard as well as a mouse

Keyboard events The trigger condition
onkeyup Triggered when a keyboard key is released
onkeydown When a keyboard key is pressed, it can recognize function keys
onkeyprss Triggered when a keyboard key is pressed, but it does not recognize function keys, such as CTRL, Shift arrows, etc

The instance

Document.onkeyup = function() {console.log(' I'm up '); } * / document. AddEventListener (' keyup ', function () {the console. The log (' I bounce '); }); // 3. When the keypress button is pressed, the function key cannot be identified. Such as CTRL, shift left and right arrows document. AddEventListener (' keypress ', function () {the console. The log (' I press press '); }) // 2. When the keyDown button is pressed, the function key can be identified. Such as CTRL, shift left and right arrows document. AddEventListener (' keydown ', function () {the console. The log (' I pressed down); }); Keydown -> keypress -> keyup </script>Copy the code
KeyCode determines which key the user presses
<script> // The keyCode attribute in the keyboard event can get the corresponding ASCII code value // 1. Our keyup and keyDown events are case insensitive a and A, resulting in both 65 // 2. Our keypress events to distinguish the letter case, a 97, and a got the 65 document. AddEventListener (' keyup ', function (e) {the console. The log (' up: '+ e.k eyCode); If (e.keycode === 65){alert(' you pressed a key '); // We can use the ASCII value returned by keyCode to determine which key the user pressed. } else {alert(' You did not press a key '); }}); document.addEventListener('keypress', function(e) { console.log('press: ' + e.keyCode); }) </script>Copy the code
Simulation jingdong key input content case

When the user clicks S, the cursor is automatically positioned in the text box

Case analysis

1, core idea: detect whether the user pressed the S key, if pressed the S key, the cursor is positioned in the search box

2. Use keyCode in the keyboard event object to determine whether the user pressed the S key

3, search the box to get focus: use the focus() method in JS

The instance

<body>
    <input type="text">
    <script>
        var search = document.querySelector('input');
        document.addEventListener('keyup', function(e) {
            //console.log(e.keyCode);
            if(e.keyCode === 83) {
                search.focus();
            }
        })
    </script>
</body>
Copy the code
Simulate jingdong express tracking number query

Requirement: When we enter content in the text box, the text box will automatically display large size content.

Case analysis

  • When the tracking number is entered, the large font box (CON) above is displayed (here the size is larger).
  • Forms detect user input: Add keyboard events to forms
  • We also get the value from the tracking number and assign the value to the con box as the innerText
  • If the tracking number content is empty, hide the large type box (CON) box

The instance

<body> <div class="search"> <div class="con">123</div> <input type="text" placeholder=" <script> var con = document.querySelector('.con'); var jd_input = document.querySelector('.jd'); jd_input.addEventListener('keyup', function() { if(this.value == ''){ con.style.display = 'none'; } else { con.style.display = 'block'; con.innerText = this.value; }}); Jd_input.addeventlistener ('blur', function() {con.style.display = 'none'; }); Jd_input.addeventlistener ('focus', function() {if(this.value! == ''){ con.style.display = 'block'; } }) </script> </body>Copy the code

Note that the keyDown and KeyPress events in the textbox are triggered before the text falls into the textbox.

3.BOM

The target

What is BOM

The ability to know the browser’s top-level object window

Ability to write page loading events and notes

Be able to write two timer functions and tell the difference

Be able to say JS execution mechanism

The location object can be used to jump between pages

The ability to know the properties involved in the Navigator object

You can use the methods provided by History to implement a page refresh

Summary of BOM

BOM is the browser object model. It provides objects that interact with the browser window independently of content. The core of BOM is window. Including forward and backward pages, adjust window size, slide page.

A BOM is made up of a series of related objects, each of which provides a number of methods and attributes.

BOM lacks standards. The standardisation body for JavaScript syntax is ECMA, the standardisation of DOM is W3C, and BOM was originally part of the Netscape browser standard.

The DOM and BOM

DOM

  • Document Object Model
  • DOM is about treating a document as an object
  • The top-level object of the DOM is document
  • DOM is primarily about manipulating page elements
  • DOM is a W3C standard specification

BOM

  • Browser object Model
  • Think of the browser as an object
  • The top-level object of the BOM is window
  • BOM learns about objects that a browser window interacts with
  • BOM is defined by browser vendors on their browsers and is not compatible with each other

Window contains document, location, navigation, screen, and history

The structure of the BOM

The Window object is the top-level object of the browser and has a dual role.

1. It is an interface for JS to access the browser window

It is a global object. Variables and functions defined in the global scope become properties and methods of the Window object.

The window can be omitted in the call. All the dialogs studied above belong to window object methods, such as alert() and prompt()

Note: a special attribute under window, window.name

Common events for window objects

Window loading event

Window.onload = function() {} or window.adDeventListener ("load", function() {});Copy the code

Window.onload is a window (page) load event that is called when the document content (including images, scripts, CSS files, etc.) is fully loaded.

Note:

With window.onload, you can write JS code at the top of a page element, because onload waits until the page is fully loaded before executing the handler function.

2. Window. onload The traditional registration event can be written only once. If there are more than one registration event, the last window.onload takes effect.

3. If addEventListener is used, there is no restriction

document.addEventListener('DOMContentLoaded', function() {})
Copy the code

The DOMContentLoaded event is triggered only when the DOM is loaded, excluding stylesheets, images, flash, and so on.

IE 9 or later is supported.

If there are a lot of pictures on the page, it may take a long time from user access to onload trigger, and the interactive effect will not be realized, which may affect the user experience. In this case, DOMContentLoaded event is more appropriate.

Resize window events

window.onresize = function() {}
window.addEventListener("resize", function() {})
Copy the code

Window. onresize is a handler that adjusts the window size to load the event and is called when triggered

Note:

1. This event is triggered whenever the window size changes by pixels

2. We often use this event for reactive layout. Window. innerWidth Width of the current screen.

The timer

The Window object gives us two very useful methods – timers

  • setTimeout()
  • setInterval()

1. The setTimeout () timer

Window.settimeout (call function, [number of milliseconds delayed])Copy the code

The setTimeout() method is used to set a timer that will execute the calling function when the timer expires.

Note:

1. Windows can be omitted

2. This function can be called by writing the function directly, or by writing the function name, or by using the string ‘function name ()’. The third method is not recommended.

3. The millisecond ellipsis of the delay is 0 by default. If writing, it must be milliseconds.

4. Since there may be many timers, we assign an identifier to the timer.

The call function setTimeout() is also called callback

Normal functions are called directly in code order.

This function, on the other hand, needs to wait until the time is up before calling this function, so it is called a callback function.

Simple understanding: a callback is a call back to the meaning of the last thing done, and then back to call this function.

Element. onclick = function{} or element.addEventListener(“click”, fn); The functions inside are also callback functions.

Automatically close the case after 5 seconds
<body>
    <img src="images/ad.jpg" alt="" class="ad">
    <script>
        var ad = document.querySelector('.ad');
        setTimeout(function() {
            ad.style.display = 'none';
        }, 5000);
    </script>
</body>
Copy the code
Stop the setTimeout() timer
window.clearTimeout(timeoutID)
Copy the code

The instance

<body> <button> click stop timer </button> <script> var BTN = document.querySelector('button'); Var timer = setTimeout(function() {console.log(' exploded '); }, 5000); Btn.addeventlistener ('click', function() {clearTimeout(timer); }) </script> </body>Copy the code

2. The setInterval () timer

Window.setinterval (callback function, [milliseconds of interval]);Copy the code

The setInterval() method calls a function repeatedly, at intervals, calling the callback function.

Note:

  • 1. Windows can be omitted.
  • 2. This function can be written directly to the function, either by the name of the function, or by the string ‘function name ()’.
  • The default is 0. If written, it must be milliseconds, indicating how many milliseconds this function is automatically called.
  • 4. Because there can be many timers, we often assign an identifier to timers.
<script> // 1. setInterval // syntax specification: window.setinterval (call function, delay time); SetInterval (function() {console.log(' continue output '); }, 1000); </script> </script> </script> </script>Copy the code
Countdown effect

Case analysis

1. The countdown is constantly changing, so you need a timer to automatically complete the change (setInterval)

2, three black boxes to store minutes

3. Three black boxes put the calculated hours, minutes and seconds using innerHTML

4, the first execution is also the interval of milliseconds, so the page will be blank just after the refresh

5. It is best to wrap the function so that it can be called once to prevent blank pages from being refreshed at the beginning

The instance

<body>
    <div>
        <span class="hour">1</span>
        <span class="minute">2</span>
        <span class="second">3</span>
    </div>
    <script>
        // 1. 获取元素 
        var hour = document.querySelector('.hour'); // 小时的黑色盒子
        var minute = document.querySelector('.minute'); // 分钟的黑色盒子
        var second = document.querySelector('.second'); // 秒数的黑色盒子
        var inputTime = +new Date('2021-9-8 19:00:00'); // 返回的是用户输入时间总的毫秒数
        countDown(); // 我们先调用一次这个函数,防止第一次刷新页面有空白 
        // 2. 开启定时器
        setInterval(countDown, 1000);
​
        function countDown() {
            var nowTime = +new Date(); // 返回的是当前时间总的毫秒数
            var times = (inputTime - nowTime) / 1000; // times是剩余时间总的秒数 
            var h = parseInt(times / 60 / 60 % 24); //时
            h = h < 10 ? '0' + h : h;
            hour.innerHTML = h; // 把剩余的小时给 小时黑色盒子
            var m = parseInt(times / 60 % 60); // 分
            m = m < 10 ? '0' + m : m;
            minute.innerHTML = m;
            var s = parseInt(times % 60); // 当前的秒
            s = s < 10 ? '0' + s : s;
            second.innerHTML = s;
        }
    </script>
</body>
Copy the code
Clear the timer clearInterval
window.clearInterval(intervalID);
Copy the code

The clearInterval() method unsets the timer previously established by calling setInterval().

Note:

1. Window can be omitted

2. The parameter is the identifier of the timer.

The instance

<body> <button class="begin"> Start timer </button> <button class="stop"> stop timer </button> <script> var begin = document.querySelector('.begin'); var stop = document.querySelector('.stop'); var timer = null; // The global variable null is an empty object begin.addEventListener('click', function() { timer = setInterval(function() { console.log('ni hao ma'); }, 1000); }) stop.addEventListener('click', function() { clearInterval(timer); }) </script> </body>Copy the code
Sending SMS Messages

After you click the button, you cannot click it again within 60 seconds to prevent repeated SMS sending.

Case analysis

1. After the button is clicked, disabled is true

Also, the content inside the button changes. Notice that the content inside the button is modified with innerHTML

3, the second speed inside is variable, so need to use a timer

4, define a variable, in the timer, constantly decreasing

5. If the variable is 0, it means that the time is up. We need to stop the timer and restore the initial state of the button.

The instance

<body> Mobile phone number: <input type="number"> <button> send </button> </button> <script> // After the button is clicked, the disabled is true. Notice that the contents of the button are modified with innerHTML. // The number of seconds in the button is changing, so we need to use a timer. // Define a variable. Var BTN = document.querySelector('button'); var time = 3; // Define the remaining seconds btn.adDeventListener ('click', function() {btn.disabled = true; Var timer = setInterval(function() {if (time == 0) {// Clear timer and restore button clearInterval(timer); btn.disabled = false; Btn. innerHTML = 'send '; time = 3; } else {btn.innerHTML = 'still' + time + 'second '; time--; }}, 1000); }) </script> </body>Copy the code

This points to the problem

The direction of this is not determined during function definition. Only when the function is executed can it be determined who this refers to. In general, this refers to the object calling it.

  1. In a global scope or normal function, this refers to the global object Window.
  2. In a method call, whoever calls this points to whom
  3. Constructor this refers to an instance of the constructor
<body> <button> click </button> <script> // this points to the problem. Console.log (this); console.log(this); console.log(this); function fn() { console.log(this); } window.fn(); window.setTimeout(function() { console.log(this); }, 1000); Var o = {sayHi: function() {console.log(this); // This refers to the object o}} o.sayhi (); var btn = document.querySelector('button'); // btn.onclick = function() { // console.log(this); //} btn.adDeventListener ('click', function() {console.log(this); Function Fun() {console.log(this); // This refers to the BTN button object. } var fun = new fun (); </script> </body>Copy the code

JS execution mechanism

Js is single threaded

  • One of the hallmarks of the JavaScript language is single-threaded, which means you can only do one thing at a time. This is because JavaScript, as a scripting language, was created to handle user interaction in a page and manipulate the DOM. For example, adding and deleting DOM elements cannot be done at the same time. It should be added before it is removed.
  • Single-threaded means that all tasks need to be queued until the previous task has finished before the next task can be executed. The problem with this is that if the JS execution takes too long, the rendering of the page will be incoherent, causing the page rendering load to feel blocked.

Synchronous and asynchronous

An example of a problem

Q: What is the result of the following code execution?

console.log(1)
setTimeout(function() {
    console.log(3);
}, 1000);
console.log(2);
Copy the code

A: After printing 1, wait 1 second before printing 3, and then print 2

To solve this problem, using the computing power of multi-core CPUS, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads. Thus, synchronous and asynchronous appear in JS.

synchronous

The execution of a task after the completion of the previous task, the order of the execution of the program and the order of the task is consistent, synchronous. For example, the cooking method of students: we should boil water to cook rice, and wait for the water to boil (10 minutes later), then to cut vegetables, fried vegetables.

asynchronous

When you’re doing one thing, because it’s going to take a long time, you can do something else while you’re doing it. For example, the asynchronous method of cooking, we boil water at the same time, use the 10 minutes, to cut vegetables, cooking vegetables.

The essential difference: Each process on this pipeline is executed in a different order.

The practice of modification

<script>        
    console.log(1);
    document.onclick = function() {
        console.log('click');
    }
    console.log(2);
    setTimeout(function() {
        console.log(3)
    }, 3000)
</script>
Copy the code

Process of executing synchronous and asynchronous tasks

Let’s look at the print order of this

<script>
    console.log(1);
    setTimeout(function() {
        console.log(3);
    }, 0);
    console.log(2);
</script>
Copy the code

Print: 1, 2, 3

Synchronization task

Synchronization tasks are executed on the main thread, forming an execution stack.

Asynchronous tasks

Asynchrony of JS is achieved through callback functions.

In general, there are three types of asynchronous tasks:

  • 1, common events, such as click, resize, etc
  • 2. Load resources, such as load and error
  • 3. Timers, including setInterval and setTimeout

Asynchronous task-related callback functions are added to the task queue (also known as message queue).

Enforcement mechanism

1. Perform the synchronization task in the stack first

2. Put the asynchronous task (callback function) into the task queue

3. Once all synchronous tasks in the execution stack are completed, the system will read the asynchronous tasks in the task queue in order. Then the asynchronous tasks that are read end the waiting state, enter the execution stack, and start to execute.

<script> console.log(1); Document.onclick = function() {console.log('click'); } console.log(2); SetTimeout (function() {console.log(3)}, 3000) </script>Copy the code

This mechanism is called an event loop because the main thread repeatedly acquires, executes, retrieves, and executes tasks.

Location object

What is a Location object?

The Window object gives us a location property that gets or sets the FORM’s URL and can be used to parse the URL. Because this property returns an object, we will also call this property a Location object.

Location The property of the object

Location object properties The return value
location.href Gets or sets the entire URL
location.host Return to host (domain name)
location.port Returns the port number, or an empty string if not written
location.pathname Returns the path
location.search Returns the parameter
location.hash Returns the content after the fragment #, commonly seen in links, anchors
Jump to page case after 5 seconds

Case analysis

  • Use a timer to make a countdown effect
  • When the time is up, jump to the page. Using the location. The href

The instance

<body> <button> click </button> <div></div> <script> var BTN = document.querySelector('button'); var div = document.querySelector('div'); Btn.addeventlistener ('click', function() {// console.log(location.href); location.href = 'http://www.itcast.cn'; }) var timer = 5; fn(); Function fn() {if (timer == 0) {location.href = 'http://www.itcast.cn'; function fn() {if (timer == 0) {location.href = 'http://www.itcast.cn'; } else {div.innerhtml = 'You will jump to home page after' + timer + 'seconds '; timer--; } } setInterval(fn, 1000); </script> </body>Copy the code
Access to the URL

Practice the transfer of data between different pages.

Case analysis

1. The first login page, which contains the submission form, submits the action to the index.html page

2, the second page, you can use the parameters of the first page, so as to achieve a data transfer effect between different pages

3. The second page can use the data of the first page by using the location.search parameter in the URL

4. In the second page, this parameter needs to be extracted.

5, the first step to remove ‘? ‘, using substr

Split (‘=’);

The instance

<body> <form action="index.html"> < form> </form> </body> </form>Copy the code
// The second page <body> <div></div> <script> console.log(location.search); / /? Uname = Andy // 1. Substr (' starting position ', cut a few characters); var params = location.search.substr(1); // uname=andy console.log(params); // 2. Split string into array split('='); var arr = params.split('='); console.log(arr); // ["uname", "ANDY"] var div = document.querySelector('div'); Div. InnerHTML = arr[1] + 'Welcome '; </script> </body>Copy the code
Location common methods
Location object method The return value
location.assign() Like href, you can jump to a page (also known as a redirect page)
location.replace() Replace the current page, because no history is recorded, so the page cannot be backward
location.reload() Reload the page, equivalent to refresh button or F5, if true forces refresh CTRL + F5

The instance

<body> <button> click </button> <script> var BTN = document.querySelector('button'); Btn.addeventlistener ('click', function() {// record browser history // location.assign('http://www.itcast.cn'); // location.replace('http://www.itcast.cn'); location.reload(true); }) </script> </body>Copy the code

The navigator object

Browsers can use the same URL to open different pages on different systems (PC, mobile).

The Navigator object contains information about the browser and has a number of properties, the most common being the userAgent, which returns the value of the User-Agent header of the server sent by the client.

The instance

if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fenne c|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) { window.location.href = ".. /H5/index.html"; // phone}else {window.location.href = "HTML file path "; / / computer}Copy the code

The history object

The Window object gives us a History object that interacts with the browser history and contains urls that the user has visited (in the browser window).

History object method role
back() You can go back
forward() Forward function
The go (parameters) The forward and backward function, if the parameter is 1, advance one page, if the parameter is -1, backward one page

Go (parameter), if the parameter is 2, it is 2 pages forward……

index.html

<a href="list.html"> </a> <button> </button> <script> var BTN = document.querySelector('button'); btn.addEventListener('click', function() { history.forward(); // history.go(1); }) </script> </body>Copy the code

list.html

<a href="index.html"> </a> </button> <script> var BTN = document.querySelector('button'); btn.addEventListener('click', function() { history.back(); // history.go(-1); }) </script> </body>Copy the code

The history object is rarely used in real development, but is found in some OA office systems.

4.PC web effects

The target

  • Can tell the function of the common offset family attribute
  • Be able to describe the functions of common client family properties
  • Be able to tell what the common Scroll properties do
  • Ability to encapsulate simple animation functions
  • Be able to write I also wheel – cast diagram case

Element offset series

An overview of the

Offset translates to offset. We can dynamically obtain the position (offset) and size of the element by using offset series related attributes.

  • Gets the element distance with the location of the parent element
  • Get the size (width and height) of the element itself
  • Note: The values returned do not have units

Commonly used attributes

Offset series attributes role
element.offsetParent Returns the parent element with positioning as the element, or body if neither parent has a unit
element.offsetTop Returns the offset of the element relative to the location above the parent element
element.offsetLeft Returns the offset of the element relative to the left border of the positioned parent element
element.offsetWidth Returns itself including padding, border, width of content area, and numeric value without units
element.offsetHeight Return itself including padding, border, height of content area, return value without units

The sample

// CSS <style> * { margin: 0; padding: 0; } .father { /* position: relative; // width: 200px; height: 200px; background-color: pink; margin: 150px; } .son { width: 100px; height: 100px; background-color: purple; margin-left: 45px; } .w { height: 200px; background-color: skyblue; margin: 0 auto 200px; padding: 10px; border: 15px solid red; } </style> //Script <body> <div class="father"> <div class="son"></div> </div> <div class="w"></div> <script> // offset Var father = document.querySelector('.father'); var son = document.querySelector('.son'); Console. log(father. OffsetTop); console.log(father. // 150 console.log(father.offsetLeft); Console. log(son.offsetleft); // 150 // It takes the parent with the location. // 195 var w = document.querySelector('.w'); // 2. You can get the size, width and height of the element by including the padding + border + width console.log(w.ofsetwidth); console.log(w.offsetHeight); // 3. Return parent with location otherwise return body console.log(son.offsetparent); // Return the parent with location otherwise return body console.log(son.parentNode); </script> </body>Copy the code

Offset is different from style

offset

  • Offset can get the style value in any stylesheet
  • The values obtained by the offset series are ununitless
  • OffsetWidth contains the padding + border + width
  • Properties such as offsetWidth are read-only and can only be obtained but cannot be assigned
  • So, we want to get the size of the element, offset is more appropriate

style

  • Style can only get style values from inline style sheets
  • Style.width gets the string with the position
  • Style.width gets a value that does not contain the padding and border
  • Style. width is a read-write property that can be obtained or assigned
  • So, if we want to change the value of an element, we need to use a style change

Element viewable client family

concept

Client translates as client, and we use the client family of attributes to get information about the visual area of an element. The client series of attributes can be used to dynamically obtain the size of the element border, element size, etc.

Client properties role
element.clientTop Returns the size of the border on the element
element.clientLeft Returns the size of the left border of the element
element.clientWidth Returns itself, including the padding, width of the content area, without borders, and number without units
element.clientHeight Returns the height of its own content area, including padding, without borders, and without units

Execute function immediately

A function that executes itself immediately without being called

The biggest advantage of the immediate function is that it creates a separate scope in which all variables are local and there are no name conflicts

grammar

(function() {})()
或者
(function() {}())
Copy the code

The instance

Function fn() {console.log(1); } fn(); / / 2. Writing can also pass parameters in / / 1. (the function () {}) () or (2) (function () {} ()); (function(a, b) { console.log(a + b); var num = 10; }) (1, 2); Function sum(a, b) {console.log(a + b); var num = 10; // local variable}(2, 3)); </script> </body> </script> </body>Copy the code

Element scroll series

Scroll translates to scroll, and we can use the related properties of scroll series to dynamically obtain the size and scrolling distance of the element.

Scroll properties role
element.scrollTop Returns the distance to the top of the reel, without units
element.scrollLeft Returns the distance to the left of the reel, without units
element.scrollWidth Returns its actual width, without borders, and a number without units
element.scrollHeight Returns its actual height, without borders, without units

Summary of three series

Three series size comparison role
element.offsetWidth Returns itself, including the padding, border, and width of the content area, without units
element.clientWidth Returns itself, including the padding, width of the content area, without borders, and number without units
element.scrollWidth Returns its actual width, without borders, and a number without units

Their main uses:

The offset family is often used to get the position of an element, offsetLeft, offsetTop

2. Client is often used to get the size of an element, clientWidth, clientHeight

3, Scroll is often used to obtain the scrolling distance, scrollTop, scrollLeft

Animation function encapsulation

Move the box

Core principle: Continuously move the box position through timer setInterval().

Implementation steps:

1. Get the current position of the box

2. Add a movement distance to the current position of the box

3. Repeat this operation with timer

4. Add an end timer condition

5. Note that this element needs to be positioned to use element.style.left

<body> <div></div> <script> Get the current position of the box // 2. Make the box add 1 moving distance to the current position // 3. // add a condition to end the timer // 5. Note that this element needs to be positioned to use element.style.left var div = document.querySelector('div'); Var timer = setInterval(function() {if (div.offsetLeft >= 400) {// } div.style.left = div.offsetLeft + 1 + 'px'; }, 30); </script> </body>Copy the code

Animation function simple encapsulation

Note that the function needs to pass two parameters, the animation object and the distance to be moved.

<body> <div></div> <span> </span> <script> Target) {var timer = setInterval(function() {if (obj.offsetLeft >= target) { } obj.style.left = obj.offsetLeft + 1 + 'px'; }, 30); } var div = document.querySelector('div'); var span = document.querySelector('span'); // Call animate(div, 300); animate(span, 200); </script> </body>Copy the code

Add different timers for different objects

</div> <span> </span> <script> // var obj = {}; // obj.name = 'andy'; Function animate(obj, target) {function animate(obj, target) {function animate(obj, target) { Because there are too many timers on // The solution is to have only one timer run on the element // Clear the previous timer and keep the current timer run clearInterval(obj.timer); Obj. timer = setInterval(function() {if (obj.offsetLeft >= target) {// Stop the timer clearInterval(obj.timer); } obj.style.left = obj.offsetLeft + 1 + 'px'; }, 30); } var div = document.querySelector('div'); var span = document.querySelector('span'); var btn = document.querySelector('button'); // Call animate(div, 300); btn.addEventListener('click', function() { animate(span, 200); }) </script> </body>Copy the code

Principle of slow motion animation

A slow animation is an element that moves at a different speed, most commonly to a slow halt.

Ideas:

1, let the box each moving distance slowly smaller, the speed will slowly fall down

2. Core algorithm :(target value – current position) / 10, as the distance step of each move.

3, stop condition is: let the current box position equal to the target position to stop the timer.

</span> </span> </span> </span> Let the box move a smaller distance each time, the speed will slow down. // 2. Core algorithm :(target value - current position) / 10 as the distance step for each move // 3. Function animate(obj, target) {function animate(obj, target) {// clearInterval(obj. Timer); Obj. timer = setInterval(function() {var step = (target-obj. offsetLeft) / 10; If (obj.offsetLeft == target) {// Stop the animation essentially stops the timer clearInterval(obj.timer); } // change the step size to a smaller one :(target value - current position) / 10 obj.style.left = obj.offsetleft + step + 'px'; }, 15); } var span = document.querySelector('span'); var btn = document.querySelector('button'); Btn.addeventlistener ('click', function() {animate(span, 500); }) // Constant animation is the current position of the box + fixed value 10 // slow animation is the current position of the box + changed value (target value - current position) / 10) </script> </body>Copy the code

Common web special effects cases

Web page rotation map

Common development frameworks on mobile

The framework outlined

Framework, as the name implies, is a set of architecture, which will provide users with a relatively complete solution based on its own characteristics. The controller of the frame is in the frame itself, and the user should develop according to some specification specified by the frame lock.

Plug-ins generally exist specifically to solve a problem, and their functions are single and relatively small.

Common front-end frameworks include Bootstrap, Vue, Angular, React, etc. It can develop both PC side and mobile side.

Common front-end mobile terminal plug-ins include Swiper, Superslid, and iscroll.

  • Framework: big and complete, a whole set of solutions
  • Plug-ins: Small, specific, functional solutions.

Bootstarp

Bootstarp is a simple, intuitive, powerful front-end development framework that makes Web development faster and easier.

It can be developed on PC as well as mobile.

Bootstrap JS plug-in

1. Introduce relevant JS files

2. Copy the HTML structure

3, modify the corresponding style

4. Modify the relevant JS parameters

The local store

The target

  • Able to write sessionStorage data storage and access
  • Able to write localStorage data storage and access
  • Be able to tell the difference between the two

With the rapid development of the Internet, web-based applications are becoming more and more common, but also more and more complex. In order to meet various needs, large amounts of data are often stored locally. The HTML5 specification proposes relevant solutions.

Local Storage feature

1. Data is stored in the user’s browser

2, easy to set, read, and even page refresh without loss of data

3, large capacity, sessionStorage about 5M, localStorage about 20M

4, can only store strings, can encode the object json.stringify () store

sessionStorage

1. The lifecycle is to close the browser window

2. Data can be shared in the same window (page)

3. Store and use in the form of key-value pairs

Storing data:

sessionStorage.setItem(key, value)
Copy the code

Get data:

sessionStorage.getItem(key)
Copy the code

Delete data:

sessionStorage.removeItem(key)
Copy the code

Delete all data:

sessionStorage.clear()
Copy the code

The instance

<body> <input type="text"> <button class="set"> </button> <button class="get" Class ="remove"> delete data </button> <button class="del"> delete all data </button> <script> // get local storage values //console.log(localStorage.getItem('username')); var ipt = document.querySelector('input'); var set = document.querySelector('.set'); var get = document.querySelector('.get'); var remove = document.querySelector('.remove'); var del = document.querySelector('.del'); Set.addeventlistener ('click', function() {var val = ipt.value; sessionStorage.setItem('uname', val); sessionStorage.setItem('pwd', val); }); Get.addeventlistener ('click', function() {console.log(sessionStorage.getitem ('uname')); }); Remove. AddEventListener (' click ', function () {/ / when we click after, she removed the data in a form sessionStorage. RemoveItem (' uname); }); Del.addeventlistener ('click', function() {// Clear all sessionStorage.clear(); }) </script> </body>Copy the code

localStorage

1, the life cycle is permanent, unless manually deleted, otherwise the closed page will exist.

2. Multiple Windows (pages) can be shared (the same browser can be shared)

3. Store and use in the form of key-value pairs

Storing data:

localStorage.setItem(key, value)
Copy the code

Get data:

localStorage.getItem(key)
Copy the code

Delete data:

localStorage.removeItem(key)
Copy the code

Delete all data:

localStorage.clear()
Copy the code

The instance

<body> <input type="text"> <button class="set"> </button> <button class="get" </button> <script> var ipt = document.querySelector('input'); var set = document.querySelector('.set'); var get = document.querySelector('.get'); var remove = document.querySelector('.remove'); var del = document.querySelector('.del'); set.addEventListener('click', function() { var val = ipt.value; localStorage.setItem('username', val); }); get.addEventListener('click', function() { console.log(localStorage.getItem('username')); }); remove.addEventListener('click', function() { localStorage.removeItem('username'); }); del.addEventListener('click' , function() { localStorage.clear(); }); </script> </body>Copy the code

Remember the user name case

If you select Remember user name, the next time the user opens the browser, the last login user name will be automatically displayed in the text box.

Case analysis

Save the data for local storage

Close the page, you can also display the user name, so use localStorage

Open the page and check whether the user name exists. If so, display the user name in the form and check the checkbox

The change event occurs when the checkbox changes

If it is checked, it is stored, otherwise it is removed

<body> <input type="text" id="username"> <input type="checkbox" name="" id="remember" document.querySelector('#username'); var remember = document.querySelector('#remember'); if (localStorage.getItem('username')) { username.value = localStorage.getItem('username'); remember.checked = true; } remember.addEventListener('change', function() { if (this.checked) { localStorage.setItem('username', username.value) } else { localStorage.removeItem('username'); } }) </script> </body>Copy the code