Notes written following Mr. Pink's course
JS Basics
1. Operators
1.1 Self-Incrementing Operators
var e = 10;
var f = e++ + ++e;
// 1. e++ = 10 e = 11
// 2. e = 12 ++e = 12
console.log(f); // 22
- 1
- 2
- 3
- 4
- 5
1.2 Logical Operators
1.2.1 Logic and
If there is a false, there must be a false, both sides are true before returning true
For values and expressions:
Syntax: Expression 1 && Expression 2
If the value of the first expression is true, expression 2 is returned
If the value of the first expression is false, return expression 1
console.log( 123 && 456 ); // 456
console.log( 0 && 456 ); // 0
console.log( 123 && 456&& 789 ); // 789
- 1
- 2
- 3
1.2.2 Logical or
If something is true, it must be true, and only returns false if both sides are false.
For values and expressions:
Syntax: expression1 || expression2
l If the value of the first expression is true, return expression 1
l If the value of the first expression is false, return expression 2
console.log( 123 || 456 ); // 123
console.log( 0 || 456 ); // 456
console.log( 123 || 456 || 789 ); // 123
- 1
- 2
- 3
1.3 Operator Prioritization
The priority decreases from top to bottom, with the top having the highest priority and the comma operator having the lowest priority.
1.4 Adding and subtracting different types of data
1.4.1 Same type of data
①Boolean type addition and subtraction
true is converted to the value 1, false is converted to the value 0 for numeric operations
② Character-type addition and subtraction
concatenate
Subtraction is performed by converting a character type to a numeric type according to the Number() method. If the converted value is NaN, the final result is NaN
1.4.2 Different types of data
Any addition to a string becomes a string.
Adding and subtracting a numeric type and a numeric string converts the numeric string to a numeric value so that the result is a numeric value
Numeric and non-numeric stringssubtract (math.), according to the Number() method to convert character type to numerical type, the result is NaN (general non-numerical value)
Boolean types and values are added and subtracted, true is converted to the value 1, false is converted to the value 0, numerical operations are performed, and the result is a numerical value
undefinedAdding and subtracting the values results in NaN
1.5 Precision Problems with Floating Point Numbers
var result = 0.1 + 0.2; // Instead of 0.3, the result is: 0.30000000000000004
console.log(0.07 * 100); // The result is not 7, but: 7.000000000000001
- 1
- 2
So: don't directly determine if two floating point numbers are equal !
2. Functions
1.1 Return Considerations
Functions all have return values
- Returns the value following the return, if any.
- Returns undefined if there is no return.
break: end the current loop body (e.g. ?for, while)
continue: jump out of the current loop and continue to execute the next loop (e.g. ?for, while)
return: not only exits the loop, but also returns the value in the ?return? statement and ends the current code within the function.
1.2 arguments
When we're not sure how many arguments to pass, we can use arguments to get them (leaving the original position of the formal parameter blank).
existJavaScriptIn this case, arguments is actually a built-in object for the current function. All functions have a built-in arguments object, which stores all the real parameters passed.
Pseudo arrays:
- have
length
causality - Storing data in an indexed manner
- Doesn't have array methods such as push, pop, etc.
function maxValue() {
var max = arguments[0];
for (var i = 0; i < arguments.length; i++) {
if (max < arguments[i]) {
max = arguments[i];
}
}
return max;
}
console.log(maxValue(2, 4, 5, 9));
console.log(maxValue(12, 4, 9));
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
1.3 How functions are declared
1.3.1 Customized function approach (named functions)
// Declaration Definition Mode
function fn() {...}
// Call
fn()
- 1
- 2
- 3
- 4
It is also called a named function because it has a name
The code to call a function can be placed either before or after the declared function
1.3.2 Function expression approach (anonymous functions)
// This is how you write a function expression; anonymous functions are terminated by a semicolon.
var fn = function(){...};
// The way the call is made, the function call must be written below the body of the function.
fn();
- 1
- 2
- 3
- 4
where fn is a variable name not a function name
Because functions do not have names, they are also called anonymous functions
Inside this fn is stored a function
The function expression approach works the same way as the variable declaration approach.
The code for the function call must be written after the function body
3. Scope
3.1 Global scopes
Acts on the environment in which all code is executed (inside the entire script tag) or a separate js file.
Variables declared under global scope are calledglobal variable(variables defined outside the function).
3.2 Local scoping (function scoping)
The code environment that acts within a function is the local scope.? It is also called a function scope because it is related to the function.
Variables declared under a local scope are calledlocal variable(Variables defined inside a function)
- Local variables can only be used inside this function
- Inside a function
var
The declared variables are local variables - The formal parameters of a function are actually local variables
3.3 Block level scopes
Block scopes are defined by the{}
Included.
No block-level scopes in Js (before ES6)
3.4 Scope Chaining
l As long as it's code, it has at least one scope.
l Local scopes written inside functions
l If there is a function within a function, then another scope can be born within this scope
l Based on the mechanism by which variables of external functions can be accessed by internal functions, a chained lookup to determine which data can be accessed by internal functions is called a scope chain.
function f1() {
var num = 123;
function f2() {
console.log( num );
}
f2();
}
var num = 456;
f1();
// Output 123, proximity principle (one layer at a time)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Scope Chaining: takes a proximity principle approach to finding the final value of a variable.
4. Pre-parsing (variable lifting)
console.log(num); // 1. Error reported, num is not defined
console.log(num);
var num = 2; //2. Output undefined
fn();
function fn() {
console.log('Print');
} //3. Output Print
fn();
var fn2 = function() {
console.log('I can't imagine.');
} //4.report an error fn2 is not a function
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
JS code is executed by the JS parser in the browser.
The JS parser is divided into two steps when running JS code:pre-analyze
cap (a poem)code execution
。
- Pre-parsing: Before JS code is executed in the current scope, the browser will declare variables with var and function declarations in memory by default (No assignment will be made) or definition.
- Code execution: Execute JS statements from top to bottom.
fn();
var fn2 = function() {
console.log('I can't imagine.');
}
// Equivalent to
var fn2;
fn();
fn2 = function(){......}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
There is variable parsing and function parsing.
// Case 4
f1();
console.log(c);
console.log(b);
console.log(a);
function f1() {
var a = b = c = 9;
console.log(a);
console.log(b);
console.log(c);
}
// Equivalent to the following code
function f1() {
var a;// Local variables
a = b = c = 9;
// Equivalent to var a = 9; b = 9; c = 9;
// b and c are assigned directly, without a var declaration, and are treated as global variables.
// Collective declaration var a = 9, b = 9, c = 9;
console.log(a);
console.log(b);
console.log(c);
}
f1();
console.log(c);
console.log(b);
console.log(a);
//Results: 9 9 9 9 9 9 Error Reporting
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
5. Objects
In JavaScript, an object is an unordered set of related properties and methods; all things are objects, such as strings, values, arrays, functions, and so on.
Objects are made up of properties and methods.
l Attributes: characteristics of things, used in objectscausalityto indicate (common noun)
l Methods: the behavior of things, used in objectsmethodologiesto indicate (common verb)
For example to save complete information about a person, you can use the array
var arr = ['Zhang Sanzhi', 'Male', 128,154];
- 1
Use the object:
person.name = 'Zhang Sanzhi';
person.sex = 'Male';
person.age = 128;
person.height = 154;
- 1
- 2
- 3
- 4
5.1 Three ways to create objects
5.1.1 Creating objects with literals
Object literal: it's the parentheses {} that contain the properties and methods that express this specific thing (object).
The {} takes the form of a key-value pair.
l Key: equivalent to the attribute name
l Value: equivalent to an attribute value, which can be of any type (numeric, string, boolean, function type, etc.)
var star = {
name : 'pink',
age : 18,
sex : 'Male',
sayHi : function(){
alert(''Hello everyone~'');
}
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
5.1.2 Creating Objects with new Objects
var andy = new Obect();
andy.name = 'pink';
andy.age = 18;
andy.sex = 'Male';
andy.sayHi = function(){
alert(''Hello everyone~'');
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
5.1.3 Creating Objects with Constructors
Constructor: a special function mainly used to initialize an object, i.e., to assign initial values to object member variables, which is always used together with the new operator. We can extract some public properties and methods from the object and encapsulate them into this function.
In js, there are two things to keep in mind when using constructors to:
- Constructors are used to create a certain class of objects withcapitalize the first letter
- Constructors have to be used with new to make sense
function Star(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
var ldh = new Star('Andy Lau', 18, 'Male');
console.log(ldh);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
5.1.4 Calls to objects
- Object Property Calls.Object. Attribute Name
- Another way to call the attribute: theObject['Attribute name'], note that the attributes inside the square brackets must be in quotes, which we'll use later with the
- object method calls:Object. MethodName()Note that the method name must be followed by parentheses.
5.1.5 Differences between Variables, Properties, Functions, and Methods
Variables: separate declaration and assignment, separate existence
Attributes: Variables inside an object are called attributes, which do not need to be declared and are used to characterize the object.
Functions: stand-alone functions that can be called by means of "function name()".
Methods: Functions inside an object are called methods, which do not need to be declared, and can be called using the "Object. Method name ()" can be called, the method is used to describe the behavior and function of the object.
5.1.6 Traversing objects
for...in statementUsed to loop over the properties of an array or object.
for (variantin object name) {
// Execute the code here
}
- 1
- 2
- 3
The variable in the grammar is customized and it needs to conform to the naming convention, usually we will write this variable as k or key.
for (var k in obj) {
console.log(k); // where k is the attribute name
console.log(obj[k]); // Here obj[k] is the value of the property
}
- 1
- 2
- 3
- 4
6. Built-in objects
6.1 Math objects
Math.PI // Pi
Math.floor() // Round down to the nearest whole number.
Math.floor(1.1) //1
Math.floor(-1.1)//-2
Math.ceil() // Round up to the nearest whole number.
Math.round() // Rounded version Round to the nearest whole number Note that -3.5 results in -3 (rounded to the nearest whole number)
Math.abs() // Absolute value
Math.max()/Math.min() // Find the maximum and minimum values
random()//Randomly return a decimal number with values in the range [0, 1), left-closed-right-open 0<=x<1
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
random number method
Get a random number between two numbers
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
//Random number multiplied by the difference of two numbers, randomly obtaining the number between the difference of two numbers, plus the least desirable number
- 1
- 2
- 3
- 4
Get a random integer between two numbers
This example returns a random integer between the specified values. This value is not less thanmin
(Ifmin
is not an integer, it is not less thanmin
(the upward integer of) and is less than (not equal to)max
。
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
// without maximum value, with minimum value
}
- 1
- 2
- 3
- 4
- 5
- 6
Get a random integer between two numbers, including both numbers
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
//with maximum value, with minimum value
}
- 1
- 2
- 3
- 4
- 5
- 6
6.2 Date objects
The date object is a constructor, so we need to instantiate it before we can use it (to new)
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var dates = date.getDate();
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var day = date.getDay();
var h = date.getHours();
h = h < 10 ? '0' + h : h;
var m = date.getMinutes();
m = m < 10 ? '0' + m : m;
var s = date.getSeconds();
s = s < 10 ? '0' + s : s;
console.log('Today is' + year + 'Year' + month + 'Moon' + dates + 'Day' + days[day] + ' ' + h + ':' + m + ':' + s);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
6.3 Array objects
6.3.1 Detecting if it is an array
The instanceof operator, which determines whether an object is of a certain type.
() is used to determine whether an object is an array or not, isArray() is the method provided in HTML5
var arr = [1, 23];
var obj = {};
console.log(arr instanceof Array); // true
console.log(obj instanceof Array); // false
console.log(Array.isArray(arr)); // true
console.log(Array.isArray(obj)); // false
- 1
- 2
- 3
- 4
- 5
- 6
6.3.2 Methods for Adding and Removing Array Elements
var arr = [1500, 1200, 2000, 2100, 1800];
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] < 2000) {
newArr.push(arr[i]);
}
}
console.log(newArr);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
6.3.3 Sorting arrays
[External link image dump failed, the source site may have anti-piracy chain mechanism, it is recommended to save the image and upload it directly (img-0FliWGdO-1618047172807)(/2021/03/23/)]
var arr = [1, 64, 9, 6];
arr.sort(function(a, b) {
return b - a; // Descending
// return a - b; // ascending
});
console.log(arr)
- 1
- 2
- 3
- 4
- 5
- 6
6.3.4 Array indexing methods
lastIndexOf() starts from the back.
6.3.5 Converting Arrays to Strings
arr.join(';')
arr.toString()
- 1
- 2
6.3.6 Joining, Intercepting, Deleting
6.4 String Objects
6.4.1 Basic packaging types
To facilitate manipulation of basic data types, JavaScript?also provides three special reference types: String, Number, and Boolean.
Basic Packaging TypesIt is the wrapping of simple datatypes into complex datatypes so that the basic datatypes have properties and methods.
//? What's wrong with the following code?
var str = 'andy';
console.log(str.length);
- 1
- 2
- 3
By definition, basic data types do not have attributes and methods, while objects have attributes and methods, but the above code can be executed, this is because js will wrap the basic data types into complex data types, the execution process is as follows:
//1. Generate temporary variables to wrap simple types into complex data types
var temp = new String('andy');
//2. Assigning values to the character variables we declare
str = temp;
//3. Destruction of temporary variables
temp = null;
- 1
- 2
- 3
- 4
- 5
- 6
6.4.2 String immutability
It means that the value inside is immutable, and although it appears that the contents can be changed, it is actually the address that has changed and a new memory space has been opened in memory.
var str = 'abc';
str = 'hello';
// When str is reassigned, the constant 'abc' is not modified and remains in memory
// Reassigning a value to a string reopens up space in memory, a feature that makes strings immutable
// Due to the immutability of strings, there are efficiency issues when splicing large numbers of strings.
var str = '';
for (var i = 0; i < 100000; i++) {
str += i;
}
console.log(str); // This result takes a lot of time to display because it requires constant opening of new space
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
6.4.3 Return position by character
var str = 'The spring wind of reform is blowing all over the land, the Chinese people are really competitive!'
console.log(str.indexOf('Medium'));
console.log(str.indexOf('Medium', 5));
// The output is the same, because he just doesn't look up the characters before (not including) the full character.
- 1
- 2
- 3
- 4
6.4.4 Returning characters based on position (emphasis added)
6.4.5 String manipulation methods (emphasis)
6.4.6 Replacing strings - replace() method
The replace() method is used to replace some characters with others in a string.
replace(the string to be replaced, the string to be replaced with);
- 1
Replace only the first character
6.4.7 Splitting strings - split() method
var str = 'a,b,c,d';
console.log(str.split(',')); // Returns an array [a, b, c, d].
- 1
- 2
6.4.8 Case conversion
toUpperCase() //Convert to uppercase
toLowerCase()// Convert lower case
- 1
- 2
7. Simple and complex types
7.1 Definitions
Simple types are also called basic data types or value types and complex types are also called reference types.
- Value type: Simple data type/basic data type, in the storage of the variable is stored in the value itself, so it is called the value type string, number, boolean, undefined, null
- Reference type: complex data type, in the storage of the variable stored only in the address (reference), so it is called the reference data type
Objects (system objects, custom objects) created by the new keyword, such as Object, Array, Date, etc.
7.2 Heap and Stack
1, stack (operating system): automatically allocated by the operating system to release the value of the parameters of the storage function, the value of local variables, etc.. Its operation is similar to the stack in the data structure;
Simple data types are stored on the stack
2, heap (operating system): storage of complex types (objects), generally allocated by the programmer to release, if the programmer does not release, recycled by the garbage collection mechanism.
Complex data types are stored in the heap
[External link image dump failure, the source station may have anti-piracy chain mechanism, it is recommended to save the image directly uploaded (img-3lTujijq-1618047249923)(/2021/03/25/)]
Note: There is no concept of stack in JavaScript. The stack makes it easier to understand some of the ways in which the code is executed, making it easier to learn other languages in the future.
7.3 Memory Allocation for Simple Types
Value types (simple data types): string, number, boolean, undefined, null
Data for value type variables is stored directly in the variable (stack space)
7.4 Memory Allocation for Complex Types
Reference type variables (stack space) hold addresses, real object instances are stored in heap space
7.5 Simple Type Passing
The formal parameter of a function can also be regarded as a variable. When we pass a variable of value type as an argument to the formal parameter of a function, we actually make a copy of the value of the variable in the stack space to the formal parameter, so any modification to the formal parameter inside the method will not affect the external variable.
function fn(a) {
a++;
console.log(a);// Output 11 here
}
var x = 10;
fn(x);
console.log(x);// Output 10 here
- 1
- 2
- 3
- 4
- 5
- 6
- 7
7.6 Passing Parameters of Complex Types
The formal parameter of a function can also be viewed as a variable. When we pass a reference type variable to the formal parameter, we are actually copying the heap address of the variable that is saved in the stack space to the formal parameter. The formal parameter and the real parameter are in fact saved with the same heap address, so they operate on the same object.
function Person(name) {
this.name = name;
}
function f1(x) { // x = p
console.log(x.name); // 2. Outputting Andy Lau
x.name = "Jacky Cheung.";
console.log(x.name); // 3. Exporting Jacky Cheung
}
var p = new Person("Andy Lau.");
console.log(p.name); // 1. Outputting Andy Lau
f1(p);
console.log(p.name); // 4. Exporting Jacky Cheung
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
Web APIs
1. Introduction
1.1 JS Composition
1.2 API and Web API Summary
- API is an interface for us programmers to help us achieve a certain functionality, we can use it as long as we don't have to worry about how to implement the internal
- Web API is mainly for the browser to provide the interface, mainly for the browser to do interactive effects.
- Web APIs generally have inputs and outputs (function passes and return values), and many of the Web APIs are methods (functions)
- Learning about Web APIs can be done along the same lines as learning about built-in object methods.
2.1 Introduction to DOM
Document Object Model (DOM), is a standard programming interface for working with Extensible Markup Language (HTML or XML) recommended by the W3C organization.
The W3C has defined a series of DOM interfaces through which the content, structure and style of a web page can be changed.
2.2 DOM tree
DOM tree Also known as the document tree model, mapping documents into a tree structure, through the node object to its processing, the results of processing can be added to the current page.
- document: a page is a document, the DOM uses document to represent the
- Nodes: All content in a web page is a node in the document tree (labels, attributes, text, comments, etc.), represented by node
- Tag nodes: all the tags in a web page, usually called element nodes, also referred to as "elements", using element to indicate that
DOM treats all of the above as objects
2.3 Getting Elements
2.3.1 Obtaining by ID
Syntax: document.getElementById(id)
Role: Based onIDGet element object
Parameters: id value, case-sensitive string
Return value: the element object ornull
- 1
- 2
- 3
- 4
2.3.2 Getting by tag name
Syntax: ('tag name') or ('tag name')
Function: Get the element object according to the tag name
Arguments: tag name
Return Value: a collection of element objects (pseudo array, the elements of the array are element objects)
- 1
- 2
- 3
- 4
Attention:
-
Since we get a collection of objects, we need to traverse it if we want to manipulate the elements inside.
-
Getting element objects is dynamic
-
When only one element is retrieved, the return is still a pseudo-array, but there is only one array object.
-
If no element is retrieved, an empty pseudo-array is returned.
Case Code
<body>
<div id="time">2019-9-9</div>
<ul>
<li>hey,man</li>
<li>hey,man</li>
</ul>
<ol id="ol">
<li>Oh, I don't know.</li>
</ol>
<script>
// Fetch with getElementById
var timer = document.getElementById('time');
console.log(timer);
console.log(typeof(timer));
console.dir(timer);
// Get elements by tag name
var lis = document.getElementsByTagName('li');
console.log(lis);
console.log(lis[0]);
for (var i = 0; i < lis.length; i++) {
console.log(lis[i]);
}
// Select the children of a parent element
var ol = document.getElementById('ol');
console.log(ol.getElementsByTagName('li'));
</script>
</body>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
2.3.3 H5 added method acquisition
// 1 Returns a collection of element objects by class name
document.getElementsByClassName('Class name');
// 2 Returns the first element object according to the specified selector
document.querySelector('Selector');
// 3 Returns based on the specified selector
document.querySelectorAll('Selector');
- 1
- 2
- 3
- 4
- 5
- 6
case (law)
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="nav">
<ul>
<li>home page (of a website)</li>
<li>offerings</li>
</ul>
</div>
<script>
console.log(document.querySelector('.box'));
console.log(document.querySelector('.nav'));
console.log('---------------');
console.log(document.querySelectorAll('.box'));
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
2.3.4 Getting special elements (body, html)
doucumnet.body // Returns the body element object
document.documentElement // Returns the html element object
- 1
- 2
2.4 Event Basis
2.4.1 The Three Elements of Events
- Event source (who): the element that triggered the event
- Event type (what event): e.g. click click event
- Event handler (what to do): the code to be executed after the event is triggered (in the form of a function), the event handler function
<body>
<button id="btn">Tang Pak Fu (1893-1978), influential Chinese writer and poet, author of The Tang Dynasty Poetry Works</button>
<script>
var btn = document.getElementById('btn')
btn.onclick = function() {
alert("Lighting the Autumn Fragrance)
}
</script>
</body>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
2.4.2 Common mouse events
[External link image dump failed, the source station may have anti-piracy chain mechanism, it is recommended to save the image and upload it directly (img-ZzIFhXLh-1618047322309)(/2021/03/23/)]
2.5 Manipulating elements
2.5.1 Changing element content
- 1
from start to end, but it removes the html tags, as well as spaces and newlines.
- 1
The entire content from start position to end position, including html tags, while preserving spaces and newlines
<body>
<button>Display the current system time</button>
<div>sometime</div>
<p>1123</p>
<script>
// When we click the button, the text inside the div will change.
// 1. Getting elements
var btn = document.querySelector('button');
var div = document.querySelector('div');
// 2. Registering events
btn.onclick = function() {
// = '2019-6-6';
div.innerHTML = getDate();
}
function getDate() {
var date = new Date();
// We Write One Wednesday, May 1, 2019
var year = date.getFullYear();
var month = date.getMonth() + 1;
var dates = date.getDate();
var arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var day = date.getDay();
return 'Today is:' + year + 'Year' + month + 'Moon' + dates + 'Day ' + arr[day];
}
</script>
</body>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
2.5.2 Attribute operations on common elements
1. innerText, innerHTML change element content
2. src, href
3. id, alt, title
- 1
- 2
- 3
<body>
<button id="ldh">Andy Lau</button>
<button id="zxy">Jacky Cheung or Hok Yau Jacky (1961-), cantopop and film star</button> <br>
<img src="images/" alt="" title="Andy Lau">
<script>
// Modify the element attribute src
// 1. Getting elements
var ldh = document.getElementById('ldh');
var zxy = document.getElementById('zxy');
var img = document.querySelector('img');
// 2. Register event handlers
zxy.onclick = function() {
img.src = 'images/';
img.title = 'Xueyou Zhang Simida';
}
ldh.onclick = function() {
img.src = 'images/';
img.title = 'Andy Lau';
}
</script>
</body>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
2.5.3 Attribute manipulation of form elements
The DOM can be used to manipulate the attributes of the following form elements:
type、value、checked、selected、disabled
- 1
<body>
<button>buttons</button>
<input type="text" value="input">
<script>
// 1. Getting elements
var btn = document.querySelector('button');
var input = document.querySelector('input');
// 2. Register event handlers
btn.onclick = function() {
// The value inside the form, the text, is modified by value.
input.value = 'Clicked';
// If we want a form to be disabled and not be able to click disabled again, we want the button button to be disabled.
// = true;
this.disabled = true;
// this points to the caller of the event function btn
}
</script>
</body>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
2.5.4 Style attribute manipulation
1. In-line style operations
2. Class name style operation
- 1
- 2
Attention:
The styles in it are camel-named, such as fontSize and backgroundColor.
Modifying style operations produces in-line styles, which are more CSS-heavy.
Way 1: By manipulating the style attribute
The style attribute of an element object is also an object!
Element object.style.style attribute = value;
div.style.backgroundColor = 'purple';
- 1
Way 2: By manipulating the className attribute
Element Object.className = value;
Because class is a keyword, all use className.
className changes the class name of the element directly, overwriting the original class name.
div.className = 'first change';
- 1
2.5.5 Exclusionary ideas
If there is a group of elements and we want a certain style to be implemented on one of the elements, we need to use a circular exclusionary thinking algorithm:
- All elements are fully unstyled (taking out everyone else)
- Styling the current element (leave me alone)
- Be careful not to reverse the order. Take out the others first, then set yourself up.
2.5.6 Customizing Attributes
2.5.6.1 Getting attribute values
element.properties
('Attributes');
- 1
- 2
Distinction:
element. Attributes Getting the values of built-in attributes (attributes that come with the element itself)
('Properties'); mainly to get customized properties (standard) Properties customized by our programmers
2.5.6.2 Setting property values
element.attributes = 'value' Sets the built-in attribute value.
('attribute', 'value');
- 1
- 2
Distinction:
element.attributes Setting built-in attribute values
('Properties'); mainly sets customized properties (standard)
2.5.6.3. removal of attributes
('Properties').
- 1
2.5.7 H5 Custom Attributes
Purpose of custom attributes: It is to save and use data. Some data can be saved to the page without having to save it to the database.
Custom attributes are obtained via getAttribute('attribute').
However, some custom attributes are ambiguous and it is not easy to determine whether they are built-in or custom attributes of an element.
H5 specifies that the custom attribute data-begins with the attribute name and assigns a value.
<div data-index="1"></div>
- 1
Or use JS to set
('data-index', 2)
- 1
Getting Properties
CompatibilityGet ('data-index').
H5 added
or ['index']
- 1
- 2
- 3
dateset can only get custom attributes that start with data-.
2.6 Node Operation
[External link image dump failed, the source site may have anti-piracy chain mechanism, it is recommended to save the image and upload it directly (img-31Uh43UB-1618047359427)(/2021/03/23/)]
Nodes have at least nodeType, nodeName, and nodeValue.
Essential Attributes.
- Element node nodeType is 1
- Attribute node nodeType is 2
- Text node nodeType is 3 (text node contains text, spaces, newlines, etc.)
In our practical development, node operations mainly operate on element nodes
hierarchy of nodes
2.6.1 Parent nodes
node.parentNode
- 1
The parentNode attribute returns a nodeNearest parent node
Returns null if there is no parent node
2.6.2 Subnodes
1 (standard)
- 1
Returns a collection containing the children of the specified node that is updated on-the-fly.
Note: The return value contains all child nodes, including element nodes, text nodes, and so on.
If you only want to get the element nodes inside, you need to specialize. That's why we generally don't advocate the use of childNodes
var ul = document. querySelector(‘ul’);
for(var i = 0; i < ul.childNodes.length;i++) {
if (ul.childNodes[i].nodeType == 1) {
// [i] is an element node
console.log(ul.childNodes[i]);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
2 (non-standard)
- 1
is a read-only property that returns all child element nodes. It only returns the child element nodes, the rest of the nodes are not returned
Back (this is the one we're focusing on)
3
- 1
firstChild returns the first child node, or null if it can't be found. again, all nodes are included.
4
- 1
lastChild returns the last child node, or null if it can't be found. again, all nodes are included.
5
- 1
Returns the first child element node, or null if not found.
6
- 1
Returns the last child element node, or null if not found.
The firstElementChild and lastElementChild have compatibility issues and are only supported by ie9 and above.
Solution:
- If you want the first child element node, you can use the [0]
- If you want the last child element node, you can use [ - 1].
2.6.3 Sibling nodes
- 1
Returns the next sibling node of the current element, or null if it can't be found. again, contains all nodes.
2.
- 1
previousSibling Returns a sibling node to the current element, or null if it can't be found. similarly, it contains all nodes.
3.
- 1
nextElementSibling returns the next sibling node of the current element, or null if it cannot be found.
4.
- 1
previousElementSibling Returns the previous sibling node of the current element, or null if it cannot be found.
3 and 4 methods have compatibility issues, IE9 or above to support, can be as follows to encapsulate their own compatibility function compatibility issues
function getNextElementSibling(element) {
var el = element;
while (el = el.nextSibling) {
if (el.nodeType === 1) {
return el;
}
}
return null;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
2.6.4 Creating Add Nodes
Create a node
document.createElement('tagName')
// For example
document.createElement('li')
- 1
- 2
- 3
Creates the HTML elements specified by tagName. Because these elements did not exist before, the
is dynamically generated based on our requirements, so we also call it dynamically created element nodes.
Nodes need to be added after creation to have any effect
Add Node
1. node.appendChild(child)
- 1
nodeThe .appendChild() method adds a node to the end of the list of children of the specified parent. Similar to the after pseudo-element in CSS
2. node.insertBefore(child, Specify element)
- 1
() method adds a node in front of a specified child of the parent node. This is similar to the before pseudo-element in CSS.
2.6.5 Deleting nodes
(child)
- 1
() method removes a child node from the DOM and returns the removed node.
2.6.6 Replicating nodes
()
- 1
() method returns a copy of the node that called the method and is dynamic.
Attention:
- If the bracket argument is empty or false, it is a shallow copy, i.e., only the replicated node itself is cloned, not the children inside.
- If the parenthesis argument is true, it is a deep copy, which copies the node itself as well as all the children inside it.
2.6.7 Summary of Creation Elements
()
innerHTML
()
make a distinction
-
is a content stream that writes content directly to the page, which causes the page to be redrawn in its entirety
-
innerHTML writes content to a DOM node and does not cause the page to redraw in its entirety.
-
innerHTML When copying a node, the events of the original node will not be copied, and there will be memory leakage problems
-
If the page creates a lot of elements, it is recommended to use innerHTML because it is more efficient (don't splice strings, splice them as arrays)
-
It is recommended to use createElement() if the page creates fewer elements.
Summary: innerHTML is more efficient than creatElement across browsers.
3. Event Advanced
3.1 Registration of events
Adding an event to an element is called registering an event or binding an event.
There are two ways to register events: the traditional way and the method-listening registration way.
[External link image dump failed, the source site may have anti-piracy chain mechanism, it is recommended to save the image and upload it directly (img-ZCEgDe6V-1618047392677)(/2021/03/23/)]
3.1.1 addEventListener event listener (IE9 and above)
eventTarget.addEventListener(type, listener[, useCapture])
- 1
This method receives three parameters:
type: event type string, e.g. click, mouseover, don't put on here.
listener: event handling function, when the event occurs, will call the listener function
useCapture: optional parameter, is a boolean value, the default is false. After learning about DOM event flow, let's go further and learn about the
3.1.2 attachEvent event listener (just understand)
(eventNameWithOn, callback)
- 1
() method registers the specified listener with the eventTarget when the object is touched.
The specified callback function is executed when the specified event is sent.
This method receives two parameters:
eventNameWithOn: event type string, such as onclick, onmouseover, here with on
callback: event handler, called when the target triggers an event.
Note: IE8 and earlier versions support
3.1.3 Registration Event Compatibility Solution
function addEventListener(element, eventName, fn) {
// Determine if the current browser supports the addEventListener method.
if (element.addEventListener) {
element.addEventListener(eventName, fn); // The third parameter is false by default
} else if (element.attachEvent) {
element.attachEvent('on' + eventName, fn);
} else {
// Equivalent to = fn;
element['on' + eventName] = fn;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
3.2 Deletion of events
3.2.1 Deletion of event methods
// Traditional registration events
divs[0].onclick = function() {
alert('111');
// Unbind the event, because inside the event, all events are triggered before they are unbound.
divs[0].onclick = null;
}
// Listen to events, function has no name, it's an anonymous function, you can't just remove it.
// divs[1].addEventListener('click', function() {
// alert('2');
// })
// This is how it should be written
function fn() {
alert('222');
divs[1].removeEventListener('click', fn);
}
divs[1].addEventListener('click', fn);// The fn in there doesn't need to be written to call the ()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
3.2.2 Compatibility solutions
function removeEventListener(element, eventName, fn) {
// Determine if the current browser supports the removeEventListener method.
if (element.removeEventListener) {
element.removeEventListener(eventName, fn); // The third parameter is false by default
} else if (element.detachEvent) {
element.detachEvent('on' + eventName, fn);
} else {
element['on' + eventName] = null;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
3.3 DOM event flow
The tags in html are all nested within each other, we can think of the elements as a box within a box, with document being the big outermost box.
When you click on a div, at the same time you click on the div's parent element, or even the whole page.
So is the click event of the parent element executed first, or is the click event of the div executed first ?
- 1
- 2
- 3
- 4
event streamDescribes the order in which events are received from the page.
eventWhen it occurs, it will follow a specific behavior between element nodes in accordance with theSequential propagationThis propagation process is known as the DOM event stream.
For example: we registered a click event for a div in the page, when you clicked on the div, you also clicked on the body, clicked on the html, clicked on the document.
- 1
event bubbling: First introduced by IE, events are received by the most specific element and then propagated up the hierarchy to the top level of the DOM.
Event Capture: First proposed by Netscape, a process that starts at the topmost node of the DOM and then propagates down the hierarchy to the most specific element to receive it.
take note of
- JS code can only perform one of the stages of capture or bubbling.
- onclick and attachEvent only get the bubbling phase.
- The third parameter of addEventListener(type, listener[, useCapture]), if true, indicates that the event is captured when the event is captured.
If false, the event handler is called during the event bubbling phase.
Program.- In practice, we seldom use event capture, we are more concerned with event bubbling.
- Some events do not bubble, such as onblur, onfocus, onmouseenter, and onmouseleave.
- Event bubbling can sometimes be troublesome, and sometimes it can help to do certain events very cleverly, as we'll explain later.
// 3. Capture phase If addEventListener's third argument is true, then it is in the capture phase document -> html -> body -> father -> 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);
// 4. bubbling phase If addEventListener's third argument is false or omitted, then it is in the bubbling phase son -> father -> body -> html -> document
var son = document.querySelector('.son');
son.addEventListener('click', function() {
alert('son');
}, false);
var father = document.querySelector('.father');
father.addEventListener('click', function() {
alert('father');
}, false);
document.addEventListener('click', function() {
alert('document');
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
3.4 Event objects
3.4.1 What is an event object
eventTarget.onclick = function(event) {}
eventTarget.addEventListener('click', function(event) {})
// The event is the event object, which we also like to write as e or evt.
- 1
- 2
- 3
After the event occurs, a series of information related to the event data collection are put into this object, this object is the event object. It is self-generated and does not require us to write.
For example:
- Who bound this event.
- If the mouse triggers an event, it will get the information about the mouse, such as the mouse position.
- If the keyboard triggers an event, you will get information about the keyboard, such as which key was pressed.
3.4.2 Syntax for Using Event Objects
An event object is generated when an event trigger occurs and is passed as a real parameter to the event handler function.
Therefore, 1 formal parameter is declared in the event handler function to receive the event object.
3.4.3 Event object compatibility issues
The acquisition of the event object itself existscompatibility issue:
-
In standard browsers it is the browser that passes the parameters to the method, which can be retrieved by defining only the formal parameter e.
-
In IE6~8, browsers don't pass parameters to the methods, so if you need them, you need to look them up in.
Solution.
e = e || window.event;
// As long as "||" is preceded by false, it returns the value after "||" regardless of whether "||" is followed by true or false.
// As long as "||" is preceded by true, regardless of whether "||" is followed by true or false, the value preceded by "||" will be returned.
- 1
- 2
- 3
3.4.4 Common properties and methods of event objects
// Returns the object that triggered the event (in this case, the mouse click).
// this returns the object to which the event is bound.
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) {
// We bind an event to ul, so this points to ul.
console.log(this);
// We're clicking on li, so we're pointing to li.
console.log(e.target);
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
3.5 Blocking Default Behavior
var a = document.querySelector('a');
a.addEventListener('click', function(e) {
// DOM standard writing
e.preventDefault();
})
// Traditional registration
a.onclick = function(e) {
// Normal Browser
e.preventDefault();
// Low version explorer
// ;
// Everything works, no compatibility issues
// return false;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
3.6 Stopping events from bubbling
Standard way: use the stopPropagation() method inside the event object.
e.stopPropagation()
- 1
Non-standard writing: IE 6-8 utilizes the cancelBubble property of the event object.
= true;
- 1
var son = document.querySelector('.son');
son.addEventListener('click', function(e) {
alert('son');
// Stop bubbling
e.stopPropagation();
})
//father doesn't stop the bubbling, it still fires the click event on the document.
var father = document.querySelector('.father');
father.addEventListener('click', function(e) {
alert('father');
})
document.addEventListener('click', function(e) {
alert('document')
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
Compatibility Handling
if(e && e.stopPropagation){
e.stopPropagation();
}else{
window.event.cancelBubble = true;
}
- 1
- 2
- 3
- 4
- 5
3.7 Event Delegation
3.7.1 What is an Event Delegate
Delegate things to someone else to take care of them for you.
- 1
Event delegates, also known as event proxies, are called event delegates in jQuery.
To put it bluntly, instead of registering the event for the child element, register the event for the parent element and execute the processing code in the parent element's event.
- 1
3.7.2 Principle of Event Delegation
Instead of each child node setting an event listener individually, the event listener is set on its parent node, which then influences the setting of each child node using the bubbling principle.
The above example: register a click event for ul, and then use the target of the event object to find the currently clicked li, because when you click on the li, the event will bubble to the ul.
ul An event listener is triggered when there is a registered event.
3.7.3 Role of event delegates
The DOM is manipulated only once, improving the performance of the program.
case (law)
var ul = document.querySelector('ul');
ul.addEventListener('mouseover', function(e) {
e.target.style.color = 'pink';
})
ul.addEventListener('mouseout', function(e) {
e.target.style.color = 'black';
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
4 Common Mouse Events
4.1 Disable Right Mouse Button and Selection
// 1. Block right-click menu
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
})
// 2. Disable mouse selection
document.addEventListener('selectstart', function(e) {
e.preventDefault();
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
4.2 Mouse event objects
The event object represents the state of an event, a collection of information related to the event. At this stage, we mainly useMouse Event ObjectMouseEvent cap (a poem)Keyboard Event ObjectsKeyboardEvent。
// Mouse event object MouseEvent
document.addEventListener('click', function(e) {
// 1. client x and y coordinates of the mouse in the visualization area
console.log(e.clientX);
console.log(e.clientY);
console.log('---------------------');
// 2. page The x and y coordinates of the mouse in the page document.
console.log(e.pageX);
console.log(e.pageY);
console.log('---------------------');
// 3. screen x and y coordinates of the mouse on the computer screen
console.log(e.screenX);
console.log(e.screenY);
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
5 Common Keyboard Events
5.1 Keyboard Events
Note: The difference between onkeypress and the previous 2 is that it doesn't recognize function keys, such as left and right arrows, shift, and so on.
Execution sequence: down -> press -> up
5.2 Keyboard Time Objects
Keyboard Event Objects | clarification |
---|---|
keycode | Returns the ASCII value of the key |
Note: onkeydown and onkeyup are case-insensitive; onkeypress is case-sensitive.
Case in point: press the s key and the cursor is positioned in the search box
var input = document.querySelector('input');
document.addEventListener('keyup', function(e) {
// keyup and keydown are case insensitive.
if (e.keyCode == 83) {
input.focus();
}
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
Case: Jingdong Express single number query
<div class="search">
<div class="con"></div>
<input type="text" placeholder="Please enter your courier order number" class="jd">
</div>
<script>
var con = document.querySelector('.con');
var jd_input = document.querySelector('.jd');
jd_input.addEventListener('keyup', function(e) {
if (this.value == '') {
con.style.display = 'none'
} else {
con.style.display = 'block'
con.innerText = this.value;
}
})
// Show the con box when it gets focus and the content is not empty.
jd_input.addEventListener('focus', function() {
if (this.value != '') {
con.style.display = 'block'
}
})
// Lose focus to hide the con box
jd_input.addEventListener('blur', function() {
con.style.display = 'none';
})
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
6 BOM
6.1 What is BOM
BOM (Browser Object Model) meansBrowser Object ModelIt provides objects that interact with the browser window independently of the content, and its core object is window.
The BOM consists of a series of related objects, and each object provides a number of methods and properties.
There is a lack of standards for the BOM, the JavaScript syntax is standardized by ECMA, the DOM is standardized by the W3C, and the BOM was originally part of the Netscape browser standard.
6.2 Composition of the BOM
The BOM is larger than the DOM, it contains the DOM
6.3 Top-level object window
The window object is the browser's top-level object, which has a dual role.
- 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.
You can omit the window when you call it. The dialog boxes you learned earlier belong to the window object methods, such as alert(), prompt(), and so on.
Note: There is a special property under window
6.4 Common events of the window object
6.4.1 Window load events
①onload
= function(){}
or
("load",function(){});
- 1
- 2
- 3
is a window (page) loading event, when the document content is completely loaded will trigger the event (including images, script files, CSS files, etc.), on the call to the processing function.
Attention:
- You can write the JS code on top of the page element because onload waits for the page content to be fully loaded before executing the handler.
- The traditional way of registering events can only be written once, and if there is more than one, the last one will be used.
- No restriction if addEventListener is used.
window.onload = function() {
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
alert('Oh exempt~');
})
}
window.addEventListener('load', function() {
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
alert('Oh exempt~');
})
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
②DOMContentLoaded
document.addEventListener('DOMContentLoaded',function(){})
- 1
The DOMContentLoaded event is triggered only when the DOM is loaded, excluding stylesheets, images, flash and so on. (Supported by Ie9 and above)
If there are a lot of images on the page, it may take a long time from the user's access to the onload trigger, and the interactive effect can not be realized, which will definitely affect the user's experience, so it is more appropriate to use the DOMContentLoaded event at this time.
6.4.2 Resize window events
window.onresize = function(){}
window.addEventListener("resize",function(){});
- 1
- 2
It is a handler for the resize window loading event, which is called when it is triggered.
Attention:
-
This event is triggered whenever there is a pixel change in the window size.
-
We often utilize this event to accomplish responsive layouts.
The width of the current screen
// width over 800 show div, less than 800 hide div
<script>
window.addEventListener('load', function() {
var div = document.querySelector('div');
window.addEventListener('resize', function() {
if (window.innerWidth <= 800) {
div.style.display = 'none'
} else {
div.style.display = 'block'
}
})
})
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
6.5 Timers
6.5.1 setTimeout() Bomb Timer
(call function, [number of milliseconds delayed]);
- 1
The setTimeout() method is used to set a timer that executes the calling function when the timer expires.
Attention:
- window can be omitted.
- This call function canWrite the function directlyorWrite function nameOr take the **string 'function name()'** three forms. The third is not recommended
- The delay in milliseconds omitted defaults to 0. If written, it must be milliseconds.
- Because there may be many timers, we often assign an identifier to a timer.
function callback() {
console.log('2');
}
// Write the function directly, timer1 is the identifier.
var timer1 = window.setTimeout(function() {
console.log('1');
}, 5000)
// Write the function name
var timer2 = window.setTimeout(callback, 5000)
//string 'function name()', not advocated
var timer3 = window.setTimeout('callback()', 5000)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
6.5.2 Stopping the setTimeout() Timer
(timeoutID)
- 1
The clearTimeout() method cancels the timer previously established by calling setTimeout().
Attention:
- window can be omitted.
- The parameter inside is the timer identifier .
6.5.3 setInterval() Alarm Timer
(callback function, [number of milliseconds between intervals]).
- 1
setInterval() methodkeep calling (computing)A function that goes and calls the callback function every so often.
Attention:
- window can be omitted.
- This call function can be written directly to the function, or write the function name or take the string 'function name ()' three forms.
- The interval in milliseconds omitted defaults to 0. If written, it must be in milliseconds, indicating the number of milliseconds at which the function is automatically called.
- Because there may be many timers, we often assign an identifier to a timer.
- The first execution is also executed after an interval of a number of milliseconds, and then every number of milliseconds thereafter.
Case: Countdown
<div class="hour"></div>
<div class="minute"></div>
<div class="second"></div>
<script>
var hour = document.querySelector('.hour');
var minute = document.querySelector('.minute');
var second = document.querySelector('.second');
// Returns the total number of milliseconds since the user entered the time.
var inputTime = +new Date('2021-3-21 18:00:00')
// Start the timer, because the first time the timer is executed is also one second later, so it needs to be executed first.
countDown();
setInterval(countDown, 1000)
function countDown() {
// Returns the total number of milliseconds of the current time.
var nowTime = +new Date();
// times is the total number of seconds remaining
var times = (inputTime - nowTime) / 1000;
var h = parseInt(times / 60 / 60 % 24); // time
h = h < 10 ? '0' + h : h;
// Give the remaining hours to the hourly black box
hour.innerHTML = h;
// Points
var m = parseInt(times / 60 % 60);
m = m < 10 ? '0' + m : m;
minute.innerHTML = m;
// Current seconds
var s = parseInt(times % 60);
s = s < 10 ? '0' + s : s;
second.innerHTML = s;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
6.5.4 Stopping the setInterval() Timer
(intervalID);
- 1
The clearInterval() method cancels the timer previously established by calling setInterval().
Case in point: text message delivery cooling
Cell phone number:<input type="text"> <button>dispatch</button>
<!-- When the ① button is clicked, disabled is disabled.true
② at the same time the contents of the button will change, note that the contents of the button through the innerHTML change
③ The number of seconds inside the button will change, so we need to use a timer.
④ Define a variable to be decremented inside the timer.
⑤ If the variable is0 Explain that when the time comes, we need to stop the timer and restore the button to its initial state.-->
<script>
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
btn.disabled = 'true';
var s = 3;
btn.innerHTML = s + 's'
var timer = setInterval(function() {
if (s == 0) {
clearInterval(timer);
btn.disabled = false;
btn.innerHTML = 'Send';
} else {
s--;
btn.innerHTML = s + 's';
}
}, 1000)
})
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
6.6 The this pointing problem
The point of this is not determined at the time of function definition, only when the function is executed can determine to whom this is pointing, in general, this is ultimately pointing to the object that calls it.
At this stage, let's understand a couple of this pointers
-
This points to the global object window in global scopes or normal functions (note that this points to window in timers).
-
Whoever calls this in a method call points to who.
-
This in a constructor points to an instance of the constructor
6.7 JS Execution Queue
6.7.1 JS is Single-Threaded
One of the characteristics of the JavaScript language is that it is single-threaded, meaning that you can only do one thing at a time. This is because Javascript is a scripting language that was born for a purpose - JavaScript was created to handle user interactions on a page, and to manipulate the DOM. For example, when we add and remove a DOM element, we can't do it at the same time. You should add it first, and then delete it later.
Single-threading means that all tasks need to be queued, and the previous task ends before the next one is executed. The problem with this is that if the JS takes too long to execute, this can result in an inconsistent rendering of the page, leading to the feeling that the page rendering is blocking the loading of the page.
// What is the result of the execution of the following code?
console.log(1);
setTimeout(function () {
console.log(3);
}, 0);
console.log(2);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
Print 1, then 2, and finally 3.
6.7.2 Synchronous and asynchronous tasks
To solve this problem and take advantage of the computing power of multi-core CPUs, HTML5 proposed the Web Worker standard, which allows JavaScript scripts to create multiple threads. Thus, synchronous and asynchronous appeared in JS.
synchronization
The previous task is finished and then the next task is executed, the execution order of the program is consistent and synchronized with the order in which the tasks are arranged. For example, cooking is synchronized to do
Law: we have to boil water for cooking, wait for the water to boil (after 10 minutes), then go chopping and sauteing vegetables.
synchronous
You're doing something because it's something that will take a long time, and while you're doing it, you can take care of other things. Like doing
For the asynchronous approach to rice, we used the 10 minutes to chop and sauté vegetables while the water boiled.
Their essential difference: the order of execution of the processes in this pipeline is different.
6.7.3 JS execution mechanism (event loop)
-
The synchronization tasks in the execution stack are executed first.
-
Asynchronous tasks (callback functions) are placed in the task queue.
-
Once all synchronous tasks in the execution stack have been executed, the system reads the asynchronous tasks in the task queue in order, whereupon the asynchronous tasks being read
The service ends its wait state, enters the execution stack, and begins execution.
Since the main thread is constantly and repeatedly acquiring tasks, executing them, acquiring them again, and executing them again, this mechanism is known as theevent loop( event loop)。
6.8 Location Objects
6.8.1 What is a location object?
The window object gives us a location property.URL for getting or setting formsand can be used forResolving URLs . Since this property returns an object, we'll call this property a location object as well.
6.8.2 URL
universal resource locator (URL), i.e. webaddress (Uniform Resource Locator, URL) arethe InternetThe address of a standard resource on the Internet. Every file on the Internet has a unique URL that contains information indicating where the file is located and what the browser should do with it.
The general syntax format of a URL is:
protocol://host[:port]/path/[?query]#fragment
/?name=andy&age=18#link
- 1
- 2
6.8.3 Properties of the location object
Remember: href and search
Case: url pass reference
//
<form action="">
<!-- The name attribute must not be omitted, or else search will be null.-->
<input type="text" name='uname' class="uname">
<input type="submit" value="Login" class="login">
</form>
- 1
- 2
- 3
- 4
- 5
- 6
//
var div = document.querySelector('div');
console.log(location.search);
var params = location.search.substr(1);
console.log(params);
var strs = params.split('=');
console.log(strs);
div.innerHTML = 'Welcome back,' + strs[1] + '!';
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
6.8.4 Methods of the location object
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
// Record browsing history, so you can backtrack.
location.assign('');
// Doesn't record browsing history, so backward functionality is not possible
location.replace('');
location.reload(true);
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
6.9 The navigator object
The navigator object contains information about the browser. It has a number of properties, the one we use most often is userAgent, which returns the value of the user-agent header sent from the client to the server.
The following front-end code can determine which terminal the user opens the page, to realize the jump
if((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
window.location.href = ""; //Mobile phone
} else {
window.location.href = ""; //Computer
}
- 1
- 2
- 3
- 4
- 5
6.10 The history object
The window object gives us a history object to interact with the browser history. This object contains the URLs visited by the user (in the browser window).
history object is generally less used in the actual development, but will be seen in some OA office systems.
7 PC-based web effects
7.1 Element offset offset series
7.1.1 Overview of offset
offset translates to offset, and we use the offset family of related properties to dynamically get the position (offset), size, etc. of the element.
- Get the element's distance from the parent element with positioning
- Get the size (width-height) of the element itself
- Note: None of the values returned are in units
7.1.2 Distinction between offset and style
offset
-
offset allows you to get the value of a style in any style sheet.
-
The values obtained in the offset series are unitless
-
offsetWidth contains padding+border+width
-
Properties such as offsetWidth are read-only and can only be retrieved but not assigned.
-
So, if we want to get the size and position of an element, it's more appropriate to use offset
style
-
style can only get style values from in-line style sheets.
-
Obtained as a string with units
-
Gets the value without padding and border.
-
is a read-write attribute that can be obtained or assigned a value
-
So, if we want to change the value of an element, we need to change it with the style
Since we usually register touch events for elements, focus on remembering targetTocuhes
7.1.3 Cases
Case: Get the coordinates of the mouse inside the box
var div = document.querySelector('div');
div.addEventListener('mousemove', function(e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - div.offsetTop;
div.innerHTML = x + ',' + y;
})
- 1
- 2
- 3
- 4
- 5
- 6
Case :Modal box drag and drop
<body>
<div class="login-header"><a id="link" href="javascript:;">Click and the login box pops up</a></div>
<div class="login">
<div id="title" class="login-title">Member Login
<span><a id="closeBtn" href="javascript:void(0);" class="close-login">cloture</a></span>
</div>
<div class="login-input-content">
<div class="login-input">
<label for="">Username:</label>
<input type="text" placeholder="Please enter your user name" name='info[username]' id="username" class="list-input">
</div>
<div class="login-input">
<label for="">Login Password:</label>
<input type="password" placeholder="Please enter your password" name="info[password]" id="password" class="list-input">
</div>
</div>
<button id="logingBtn" class="login-button">log in</button>
</div>
<! -- Masking layer -- >!
<div id="bg" class="login-bg"></div>
<script>
var login = document.querySelector('.login');
var mask = document.querySelector('.login-bg');
var link = document.querySelector('#link');
var closeBtn = document.querySelector('.close-login');
// Show login box
link.addEventListener('click', function() {
mask.style.display = 'block';
login.style.display = 'block';
})
// Close button
closeBtn.addEventListener('click', function() {
mask.style.display = 'none';
login.style.display = 'none';
})
// Drag and drop modal boxes
// Mouse down
var titile = document.querySelector('#title');
titile.addEventListener('mousedown', function(e) {
// Mouse in box = mouse on page - box from page
var x = e.pageX - login.offsetLeft;
var y = e.pageY - login.offsetTop;
// (x + ',' + y);
// Note that the move event is inside the press event.
var move = function(e) {
// Note the units. Assignments should be made in style, not offset.
login.style.left = e.pageX - x + 'px';
login.style.top = e.pageY - y + 'px';
}
this.addEventListener('mousemove', move);
this.addEventListener('mouseup', function() {
titile.removeEventListener('mousemove', move)
})
})
</script>
</body>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
Case: imitation Jingdong magnifying glass
window.addEventListener('load', function() {
var preview_img = document.querySelector('.preview_img')
var mask = document.querySelector('.mask')
var big = document.querySelector('.big');
// Transparent yellow area and zoomed-in area for mouse passes
preview_img.addEventListener('mouseover', function() {
mask.style.display = 'block';
big.style.display = 'block';
})
// Mouse over to hide transparent yellow area and zoom area
preview_img.addEventListener('mouseout', function() {
mask.style.display = 'none';
big.style.display = 'none';
})
preview_img.addEventListener('mousemove', function(e) {
// The distance of the mouse inside the box. Be careful to see if the father is positioned, if so you need to add the father's to it
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
// Give the mask the mouse coordinates - half of the box's width and height, but don't assign it directly yet.
maskX = x - mask.offsetWidth / 2;
maskY = y - mask.offsetHeight / 2;
// If the distance between the left side of the box and the top of the box is less than 0 or more than the width of the big box - the width of the small box
// Maximum travel distance of the masking layer
var maskMax = preview_img.offsetWidth - mask.offsetWidth
if (maskX <= 0) {
maskX = 0
}
// More than big box - small box
else if (maskX >= maskMax) {
maskX = maskMax;
}
if (maskY <= 0) {
maskY = 0;
} else if (maskY >= maskMax) {
maskY = maskMax;
}
// Assignment
mask.style.left = maskX + 'px';
mask.style.top = maskY + 'px';
// Amplifier module
// Move distance of the large image = Move distance of the masking layer * Maximum move distance of the large image / Maximum move distance of the masking layer
var bigImg = document.querySelector('.bigImg');
// Maximum travel distance for large images
var bigMax = bigImg.offsetWidth - big.offsetWidth;
var bigX = maskX * bigMax / maskMax;
var bigY = maskY * bigMax / maskMax;
// (bigX);
bigImg.style.left = -bigX + 'px';
bigImg.style.top = -bigY + 'px';
})
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
7.2 Element Visualization Client Series
7.2.1 Client Overview
The client translates to client, and we use the client family of properties to get information about the visual area of an element. The client family of properties allows you to dynamically get the border size, element size, etc. of the element.
The difference between clintWidth and offsetWidth is that client does not include borders, etc.
7.2.2 Taobao Source Code Analysis
Immediate execution of the function, do not need to call, immediately on their own execution of the function, you can also pass parameters
(function(){})()
or( function(){} () )
Main effect: create an independent scope, all variables in it are local variables, avoid naming conflict problems
The following three scenarios all refresh the page and all trigger the load event.
Hyperlinks for labels
2. F5 or Refresh button (forced refresh)
3. Forward and backward buttons
In Firefox, however, there is a feature, a "round-trip cache", which not only holds the page data, but also the state of the DOM and JavaScript; in fact, it holds the entire page in memory.
So at this point the back button can't refresh the page.
In this case, you can use thePageshow eventsThis event is triggered when the page is displayed, regardless of whether the page is from the cache or not. On a page reload, the pageshow fires after the load event fires; the persisted event object determines whether the pageshow event was fired from a cached page.
Note that this event adds to the window.
7.3 Element scroll scroll series
7.3.1. scroll Overview
scroll translates to scroll, and we use the scroll family of properties to dynamically get the size, scroll distance, etc. of the element.
scrollWidth does not include the border, it includes the padding and the content area.
7.3.2 Page rolled off header
If the browser is not tall (or wide) enough to display the entire page, a scroll bar will automatically appear. When the scrollbar scrolls down, the height above the page that is hidden from view is what we call the header of the page being scrolled away. The onscroll event is triggered when the scrollbar is scrolled.
The page is rolled off the header: this can be done by getting the
If it's the left side that's been rolled
Note that the header of the element being rolled up is , or in the case of the page being rolled up, the header of the page being rolled up is
Case: imitation Taobao fixed right sidebar
<script>
var sliderBar = document.querySelector('.slider-bar')
var goTop = document.querySelector('.goTop')
var banner = document.querySelector('.banner');
var main = document.querySelector('.main');
// distance of the top from the page margins, it is safer to write it outside the function
var bannerTop = banner.offsetTop;
var mainTop = main.offsetTop;
// The position of the sidebar when the function is triggered.
var sliderBarTop = sliderBar.offsetTop - bannerTop;
// Trigger function on page scroll
document.addEventListener('scroll', function() {
// If the top of the page is curled, the value is greater than the distance from the top of the banner.
if (window.pageYOffset >= bannerTop) {
sliderBar.style.position = 'fixed';
sliderBar.style.top = sliderBarTop + 'px';
} else {
sliderBar.style.position = 'absolute';
sliderBar.style.top = '250px';
}
if (window.pageYOffset >= mainTop) {
goTop.style.display = 'block';
} else {
goTop.style.display = 'none';
}
})
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
7.3.3 Header compatibility solution for pages being rolled away
It is important to note that there are compatibility issues with the header of the page being rolled away, so the rolled away header is usually written in the following ways:
- The DTD is declared, using the
- Undeclared DTD, use
- New method and, starting with IE9, support for
function getScroll() {
return {
left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft||0,
top: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
};
}
At the time of usegetScroll().left
- 1
- 2
- 3
- 4
- 5
- 6
- 7
7.4 Summary of the three series
[External link image dump failed, the source site may have anti-piracy chain mechanism, it is recommended to save the image and upload it directly (img-QbxW8Afa-1618047757305)(/2021/03/24/)]
Their main usage:
Series Often used to get the position of an element offsetLeft offsetTop
Often used to get the size of an element clientWidth clientHeight
Often used to get scroll distance scrollTop scrollLeft
4. Pay attention to the page scrolling distance by getting the
7.5 Difference between mouseenter and mouseover
-
The mouseenter event is triggered when the mouse is moved over the element
-
Similar to mouseover, the difference between them is:
mouseover Triggered when mouse passes through its own box, and also triggered when it passes through a child box. mouseenter Triggered when mouse passes through its own box only.
The reason for this is that mouseenter doesn't bubble
With mouseenter, mouseleave will also not bubble.
7.6 Animation function encapsulation
7.6.1 Principles of animation realization
Core principle: constantly move the box position by timer setInterval().
Realization Steps:
- Get the current position of the box
- Let the box be at the current position plus 1 travel distance
- Repeat this over and over again using a timer
- Add an end timer condition
- Note that this element needs to have positioning added in order to use the
7.6.2. Animation functions record different timers for different elements
If multiple elements use this animation function, you'll have to var declare the timer each time. We can use different timers for different elements (specializing ourselves with our own timers).
// need to pass obj (animation object) and target (distance to move)
function animate(obj, target) {
// Clear the original timer first to prevent multiple timers from executing at the same time.
clearInterval(obj.timer);
// You need to declare the timer every time, and you can add different timer properties to different animation objects.
//var timer = setInterval(function() {
obj.timer = setInterval(function() {
if (obj.offsetLeft >= target) {
// Stop the animation
clearInterval(obj.timer)
} else {
obj.style.left = obj.offsetLeft + 5 + 'px';
}
}, 50)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
7.6.3 Principle of the retardation effect
Jogging animation is to vary the speed of an element's movement, most commonly by bringing the speed to a slow stop
Thoughts:
- Let the box move slowly smaller distances each time and the speed will slowly fall off.
- Core algorithm: (target value - present position ) / 10 as distance per move Step size
- Stop the timer when the current box position equals the target position.
- Note that the step values need to be rounded
//there is still a bug that the final stopping position of the moved object may not be the position we specified, because the division may be inexhaustible.
var step = (target - obj.offsetLeft) / 10;
// We need to change the step size to an integer, rounding upwards
step = Math.ceil(step);
obj.style.left = obj.offsetLeft + step + 'px';
- 1
- 2
- 3
- 4
- 5
7.6.4 Animating Functions Moving Between Multiple Target Values
You can make the animation function move from 800 to 500.
Determine if the step is positive or negative when we click the button
1. If positive, the step size is rounded up to the nearest whole number
2. If the value is negative, the step size is rounded down to the nearest whole number.
//Through the ternary function to adjust the step rounding, because the step has a positive and negative, so do not need to specifically determine the final position and the current position, direct + step can be
step = step > 0 ? Math.ceil(step) : Math.floor(step);
- 1
- 2
7.6.5 Adding Callback Functions to Action Functions
**Principle of callback function:** A function can be used as a parameter. Pass this function as a parameter to another function, when that function is executed, and then execute this function passed in, this process is called callback.
**Position where the callback function is written: **Position where the timer ends.
function animate(obj, target, callback) {
// (callback); callback = function() {} when called callback()
// Clear the previous timers first, leaving only the current one to execute.
clearInterval(obj.timer);
obj.timer = setInterval(function() {
// The step value is written to the inside of the timer.
// Change our step value to an integer and don't have problems with decimals.
// var step = ((target - ) / 10);
var step = (target - obj.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if (obj.offsetLeft == target) {
// Stopping the animation essentially stops the timer
clearInterval(obj.timer);
// The callback function is written to the end of the timer.
// if (callback) {
// // Calling Functions
// callback();
// }
callback && callback();
}
// Change the step value from 1 at a time to a slowly decreasing value Step formula: (target value - current position) / 10
obj.style.left = obj.offsetLeft + step + 'px';
}, 15);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
7.6.6 Throttle valves
Prevents continuous clicks on the rotator buttons from causing them to play too fast.
Throttle purpose: when the content of the previous function animation is executed, then go to execute the next function animation, so that the event can not be triggered continuously.
Core implementation idea: use the callback function, add a variable to control, lock function and unlock function.
Start setting a variablevar flag= true;
If(flag){flag = false; do something}
Turn off the faucet.
After the animation is executed using the callback functionflag = true
Turn on the faucet.
7.7 Common PC Effects Cases
rotating chart
window.addEventListener('load', function() {
// 1. Getting elements
var arrow_l = document.querySelector('.arrow-l');
var arrow_r = document.querySelector('.arrow-r');
var focus = document.querySelector('.focus');
var focusWidth = focus.offsetWidth;
// 2. Show and hide the left and right buttons when the mouse passes over focus.
focus.addEventListener('mouseenter', function() {
arrow_l.style.display = 'block';
arrow_r.style.display = 'block';
clearInterval(timer);
timer = null; // Clear the timer variable
});
focus.addEventListener('mouseleave', function() {
arrow_l.style.display = 'none';
arrow_r.style.display = 'none';
timer = setInterval(function() {
// Manually invoke the click event
arrow_r.click();
}, 2000);
});
// 3. Dynamically Generate Circles With a few images, I generate a few circles.
var ul = focus.querySelector('ul');
var ol = focus.querySelector('.circle');
// ();
for (var i = 0; i < ul.children.length; i++) {
// Create a small li
var li = document.createElement('li');
// Record the index number of the current circle Do this via a custom attribute
li.setAttribute('index', i);
// Insert the little li inside the ol
ol.appendChild(li);
// 4. The idea of exclusivity for circles is that we can bind the click event directly to the circle as it is being generated.
li.addEventListener('click', function() {
// Kill everyone Clear all the little li's current class name
for (var i = 0; i < ol.children.length; i++) {
ol.children[i].className = '';
}
// leave me alone current little li set current class name
this.className = 'current';
// 5. Click on the small circle to move the image, which of course moves the ul
// the distance the ul travels the index number of the circle multiplied by the width of the image note the negative value
// When we click on a small li, we get the index number of the current small li.
var index = this.getAttribute('index');
// When we click on a small li, we give num the index number of that li.
num = index;
// When we click on a small li, we circle the index number of that li.
circle = index;
// num = circle = index;
console.log(focusWidth);
console.log(index);
animate(ul, -index * focusWidth);
})
}
// Set the first little li in ol to the class name current
ol.children[0].className = 'current';
// 6. clone the first image (li) to the end of ul
var first = ul.children[0].cloneNode(true);
ul.appendChild(first);
// 7. Click the button on the right to scroll the image by one.
var num = 0;
// circle Controls the playback of a small circle.
var circle = 0;
// flag Throttle
var flag = true;
arrow_r.addEventListener('click', function() {
if (flag) {
flag = false; // Close throttle valve
// If we get to the last copied image, we need to quickly recover the left to 0 for our ul.
if (num == ul.children.length - 1) {
ul.style.left = 0;
num = 0;
}
num++;
animate(ul, -num * focusWidth, function() {
flag = true; // Open throttle valve
});
// 8. Clicking on the right button causes the circle to change along with it.
circle++;
// If circle == 4, that means we've come to the last image we cloned, and we'll recover it.
if (circle == ol.children.length) {
circle = 0;
}
// Calling Functions
circleChange();
}
});
// 9. Left-side button approach
arrow_l.addEventListener('click', function() {
if (flag) {
flag = false;
if (num == 0) {
num = ul.children.length - 1;
ul.style.left = -num * focusWidth + 'px';
}
num--;
animate(ul, -num * focusWidth, function() {
flag = true;
});
// Click on the left button and the circle changes with it You can declare another variable to control the playing of the circle.
circle--;
// If circle < 0 describes the first image, the small circle is to be changed to the 4th small circle (3)
// if (circle < 0) {
// circle = - 1;
// }
circle = circle < 0 ? ol.children.length - 1 : circle;
// Calling Functions
circleChange();
}
});
function circleChange() {
// Clear the current class name of the rest of the circles first.
for (var i = 0; i < ol.children.length; i++) {
ol.children[i].className = '';
}
// Leave the current class name of the current circle
ol.children[circle].className = 'current';
}
// 10. Autoplay Rotator
var timer = setInterval(function() {
// Manually invoke the click event
arrow_r.click();
}, 2000);
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
Back to top
- Back to top with animation
- At this point you can continue to use our wrapped animation function
- Just change all the left-related values to relate to the vertical scroll distance of the page.
- How much the page has scrolled can be determined by the
capture
- Finally, there is page scrolling, using the
(x,y)
//1. Getting elements
var sliderbar = document.querySelector('.slider-bar');
var banner = document.querySelector('.banner');
// It's the size of the header that's being rolled away. Be sure to write it outside of the scroll.
var bannerTop = banner.offsetTop
// The value that should change when our sidebar is fixed in position.
var sliderbarTop = sliderbar.offsetTop - bannerTop;
// Get the main body element
var main = document.querySelector('.main');
var goBack = document.querySelector('.goBack');
var mainTop = main.offsetTop;
// 2. The scroll event scroll
document.addEventListener('scroll', function() {
// (11);
// The header where the page is rolled up
// ();
// 3 . When the header of our page is rolled up to 172, the sidebar should be fixed.
if (window.pageYOffset >= bannerTop) {
sliderbar.style.position = 'fixed';
sliderbar.style.top = sliderbarTop + 'px';
} else {
sliderbar.style.position = 'absolute';
sliderbar.style.top = '300px';
}
// 4. When we scroll down to the main box, the goback module is displayed.
if (window.pageYOffset >= mainTop) {
goBack.style.display = 'block';
} else {
goBack.style.display = 'none';
}
})
// 3. When we click on the Back to Top module, let the window scroll to the top of the page.
goBack.addEventListener('click', function() {
// The x's and y's in there don't have units, they're just numbers.
// (0, 0);
// Since it's a window scrolling, the object is window.
animate(window, 0);
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
Somersault cloud case
- Using Animation Functions for Animation Effects
- The original starting position of the somersault cloud was 0
- When the mouse passes over a small li, make the offsetLeft position of the current small li the target value.
- Set the target value to 0 when the mouse leaves a small li
- If a small li is clicked, the current position of the li is stored as the starting position of the somersault cloud.
window.addEventListener('load', function() {
// 1. Getting elements
var cloud = document.querySelector('.cloud');
var c_nav = document.querySelector('.c-nav');
var lis = c_nav.querySelectorAll('li');
// 2. Bind events to all the little li's.
// This current is the starting position of the somersault cloud.
var current = 0;
for (var i = 0; i < lis.length; i++) {
// (1) Mouse over makes the current position of the small li the target value.
lis[i].addEventListener('mouseenter', function() {
animate(cloud, this.offsetLeft);
});
// (2) Returns to the starting position when the mouse is left.
lis[i].addEventListener('mouseleave', function() {
animate(cloud, current);
});
// (3) When we click on the mouse, we make the current position the target value.
lis[i].addEventListener('click', function() {
current = this.offsetLeft;
});
}
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
8 Web effects for mobile
8.1 Touch Screen Events
8.1.1 Overview of touch screen events
Mobile browser compatibility is better, we do not need to consider the previous JS compatibility issues, you can rest assured that the use of native JS writing effects, but mobile also has its own unique places. For example, the touch event touch (also known as a touch event) is available for both Android and IOS.
The touch object represents a touch point. A touch point may be a finger or a stylus. A touch event responds to the user's finger (or stylus) operating on the screen or trackpad.
Common touch screen events are listed below:
[External link image dump failed, the source site may have anti-piracy chain mechanism, it is recommended to save the image and upload it directly (img-h7uKE5MD-1618047817045)(/2021/03/24/)]
8.1.2 TouchEvent Objects
TouchEvent is a class of events that describes a change in the state of a finger on a touch plane (touch screen, touch pad, etc.). This type of event is used to describe one or more touch points, allowing the developer to detect the movement of a touch point, the increase and decrease of a touch point, and so on
The touchstart, touchmove, and touchend events each have their own event objects.
Touch Event Objects Focus Let's look at a list of three common objects:
[External link image dump failure, the source station may have anti-piracy chain mechanism, suggest to save the image directly uploaded (img-eTeognrt-1618047822076)(/2021/03/24/)]
Since we usually register touch events for elements, focus on remembering the
targetTocuhes
// Touch event object
// 1. Getting elements
// 2. Finger touch DOM element events
var div = document.querySelector('div');
div.addEventListener('touchstart', function(e) {
// (e);
// touches A list of all fingers that are touching the screen.
// targetTouches The list of fingers that are touching the current DOM element.
// If the listening is on a DOM element, they are both the same
// changedTouches List of fingers that have changed state from nothing to something or from something to nothing.
// Since we generally touch elements, we most often use targetTouches.
console.log(e.targetTouches[0]);
// targetTouches[0] gives you information about the first finger that is touching the dom element, such as the coordinates of the finger and so on.
});
// 3. Finger movement events on DOM elements
div.addEventListener('touchmove', function() {
});
// 4. Finger off DOM element event
div.addEventListener('touchend', function(e) {
// (e);
// When we take our finger off the screen, there is no more list of touches and targetTouches.
// But there will be changedTouches
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
8.1.3 Dragging elements on mobile
-
touchstart
、touchmove
、touchend
Dragging elements can be implemented -
But dragging an element requires the coordinates of the current finger, so we can use the
targetTouches[0]
innerpageX
cap (a poem)pageY
-
Principle of mobile dragging: Finger movement, calculate the distance moved by the finger. Then use the original position of the box + the distance moved by the finger.
-
Distance moved by the finger: the position of the finger in the slide minus the position of the finger at the beginning of the touch.
Drag and drop elements in three steps:
(1) Touch elements
touchstart
: Get the initial coordinates of the finger and the original position of the box.
(2) Move your fingertouchmove
: Calculate the slide distance of the finger and move the box
(3) Leaving the fingertouchend
:
Note: Finger movement also triggers screen scrolling so stop the default screen scrolling (); here.
8.2 Common effects for mobile
8.2.1 Example: Mobile Rotator Map
The mobile rotogram function is the same as the basic PC one.
- Can play pictures automatically
- Finger can be dragged to play the rotating chart
8.2.2 Case Study.
- autoplay function
- Turn on the timer
- For mobile mobile, you can use translate mobile
- To move the image gracefully, add a transition effect
-
Autoplay function - seamless scrolling
-
Note that we judge the condition is to wait until the picture scrolling is completed to judge, that is, after the transition is completed to judge the
-
At this point, you need to add the event transitionend to detect the completion of the transition.
-
Judgment condition: if the index number is equal to 3, it means that we have gone to the last picture, at this time, the index number should be restored to 0.
-
At this point in the image, remove the transition effect and move the
-
If the index number is less than 0, it's backwards, and the index number is equal to 2.
-
At this point in the image, remove the transition effect and move the
[External link image dump failed, the source site may have anti-piracy chain mechanism, it is recommended to save the image and upload it directly (img-KpojBiQu-1618047851368)(/2021/03/25/)]
8.3 classList Properties
The classList attribute is a new HTML5 attribute that returns the class name of the element. But ie10+ version supports it.
This property is used to add, remove and toggle CSS classes in an element. The following methods are available
Add Class:
('class name');
focus.classList.add('current');
- 1
Remove class:
('class name').
focus.classList.remove('current');
- 1
Switching Classes:
('class name').
focus.classList.toggle('current');
- 1
Note: Inside the above methods, all class names are without dots.
8.4 Click Delay Solution
The mobile click event has a 300ms delay because double tap to zoom the page on mobile screens.
Solution:
- Disable zooming. The browser disables the default double-click zoom behavior and removes the 300ms click delay.
<meta name="viewport" content="user-scalable=no">
- 1
2. Use the touch event to encapsulate this event to solve the 300ms delay.
/* The principle is:
1. when our finger touches the screen, record the current touch time
2. when our finger leaves the screen, subtract the time of touching from the time of leaving. 3.
3. if the time is less than 150ms, and there is no slide on the screen, then we define it as a click.
// Wrap the tap to solve the click 300ms latency.
function tap (obj, callback) {
var isMove = false;
var startTime = 0; // Record the time variable at the time of the touch
obj.addEventListener('touchstart', function (e) {
startTime = Date.now(); // Record touch time
});
obj.addEventListener('touchmove', function (e) {
isMove = true; // See if there's a slide. A slide counts as a drag, not a click.
});
obj.addEventListener('touchend', function (e) {
if (!isMove && (Date.now() - startTime) < 150) { // Counts as a click if the finger touch and leave time is less than 150ms.
callback && callback(); // Execute the callback function
}
isMove = false; // Invert Reset
startTime = 0;
});
}
//call
tap(div, function(){ // Execute the code });
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
3. Use a plugin. fastclick plugin to solve the 300ms delay.
9 Commonly used development plug-ins for mobile
9.1 What is a plug-in
Dynamic end of the requirements of the rapid development, so we often resort to some plug-ins to help me complete the operation, then what is the plug-in it?
JS plugin is a js file , it follows a certain specification written to facilitate the program to show the effect of having a specific function and easy to call . Such as rotating charts and waterfall plug-ins.
Characteristics: It generally exists specifically to solve a problem, it has a single function, and it is relatively small.
It's one of the simplest plug-ins we've ever written.
The fastclick plugin solves the 300ms delay. Use the delay
GitHub official website address: /ftlabs/fastclick
9.2 Use of plug-ins
- Introduces the js plugin file.
- Use in accordance with the prescribed grammar.
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function() {
FastClick.attach(document.body);
}, false);
}
- 1
- 2
- 3
- 4
- 5
9.3 Using the Swiper plug-in
Chinese official website address: /
- Introduces plug-in related files.
- Use in accordance with the prescribed syntax
9.4 Other common plug-ins for mobile
superslide: http:///
iscroll: /cubiq/iscroll
9.5 Video plug-ins for mobile
H5 gives us the video tag, but browsers support it differently.
Different video format files we can solve by source.
But the appearance of the style, as well as pause, play, full screen and other features we can only write their own code to solve.
This time we can use the plugin method to create it.
We can modify the size, color, position and other styles of an element through JS.
9.6 Summary of plug-in usage
- Confirmation of the functionality implemented by the plugin
- Go to the official website for instructions
- Download plug-ins
- Open the demo example file, check the relevant files that need to be introduced, and introduce the
- Copy the structure html, style css, and js code in the demo example file.
10 Common development frameworks for mobile
10.1 Overview of the framework
A framework, as the name suggests, is a set of structures that provide a more complete solution to the user based on its own characteristics. The control of the framework is in the framework itself, and the user has to develop according to certain specifications set out in the framework.
Plug-ins generally exist specifically to solve a problem, are monofunctional, and are relatively small.
Commonly used frameworks for front-end areBootstrap、Vue、Angular、React etc. Can develop for both PC and mobile
Commonly used mobile plugins for front-end areswiper、superslide、iscrolletc.
Framework: Large and comprehensive, complete set of solutions
Plug-ins: small and specialized, a solution for a certain function
10.2 Bootstrap
Bootstrap is a clean, intuitive and powerful front-end development framework that makes web development faster and easier.
It can develop for PC as well as for mobile
Bootstrap JS plugin usage steps:
1. Introduce the relevant js file
2. Copy the HTML structure
3. Modify the corresponding style
4. Modify the corresponding JS parameters
11 Local storage
With the rapid development of the Internet, web-based applications are becoming more and more common, and at the same time becoming more and more complex, in order to meet a variety of needs, there will often be a large amount of data stored locally, the HTML5 specification proposes a relevant solution.
11.1 Local storage characteristics
1、Data stored in the user's browser
2, setup, easy to read, even page refresh does not lose data
3, larger capacity, sessionStorage about 5M, localStorage about 20M
4, can only store strings, you can encode the object () storage
11.2
1. The life cycle is to close the browser window
2, in the same window (page) under the data can be shared
3、Store the use in the form of key-value pairs
Storing data:
sessionStorage.setItem(key, value)
- 1
Get the data:
sessionStorage.getItem(key)
- 1
Delete data:
sessionStorage.removeItem(key)
- 1
Empty data: (all cleared out)
sessionStorage.clear()
- 1
11.3
1, the declaration cycle is permanently in effect, unless manually deleted, or close the page will also exist
2, you can share multiple windows (pages) (the same browser can be shared)
3、Store the use in the form of key-value pairs
Storing data:
localStorage.setItem(key, value)
- 1
Get the data:
localStorage.getItem(key)
- 1
Delete data:
localStorage.removeItem(key)
- 1
Empty data: (all cleared out)
localStorage.clear()
- 1