Painstaking efforts to sort out the complete collection of JavaScript knowledge points, super detailed suggestions collection!!!

Keywords: Javascript html5 html

1, Syntax and variables

(1) . front end third floor

(2) Writing position of JS

 

(3) . output statement  

(4) . variable declaration promotion

Variable declaration promotion: you can use a variable declared later in advance without throwing an exception

Before executing all code, JS has a pre parsing stage, which will pre read the definitions of all variables

2, Basic data type

(1) Two types of data types in and JavaScript

 

(2) , typeof operator

The typeof operator can detect the type of a value or variable

(3) typeof test results of five basic data types

 

(4) , number type

All numbers, regardless of size, integer, float, positive or negative, are numeric types


Larger numbers or smaller decimals (smaller absolute values) can be written as scientific counting

 

(5) , digits of different base numbers  

 

(6) , a special numeric value NaN

NaN means "not a number" in English, that is, it is not a number, but it is a numeric value

(7) , string type

  • String is human's natural language
  • The string should be enclosed in quotation marks, either double quotation marks or single quotation marks

(8) String splicing

The plus sign can splice multiple strings


(9) Splicing of, strings, and variables

Empty string

Sometimes you need to use an empty string, just write a closed quotation mark pair

The length property of the string

The length property of the string indicates the length of the string

 

(10) Common methods of string  

(11) , charAt() method

Function: get the character at the specified position


 

 

(12) , substring() method




  (13) , substr() method

 

  (14) , slice() method

 

 

  (15) Comparison and summary of the three

 

(16) , toUpperCase() and toLowerCase()  

(17) , indexOf ()  

 

 

(18) , BOOlean (BOOlean type)  

 

 

 

 

(19) , Undefined

The default value of an unassigned variable is undefined, and the undefined type is undefined, that is, undefined is both a value and a type. This type has only its own value

Variable promotion

When a variable is declared promoted, the value of the variable is also undefined

(20) , null type

  • A null object represents an empty object, which is an empty object
  • When we need to destroy objects, arrays or delete event listeners, we usually set them to null

 

 

(21) . conversion of data type

Using the Number() function

 

Use the parseInt() function  

 

Use the parseFloat() function  

 

 

 

 

(22) Introduction to complex data types  

 

3
true
NaN
Infinity

 

bcd
bc
''
bc

 

(23) , expressions, and operators

 

Type of expression

Arithmetic, relation, logic, assignment, synthesis

(24) , arithmetic operators

By default, multiplication and division takes precedence over addition and subtraction. If necessary, parentheses can be used to change the order of operations

 

Two functions of plus sign  

 

 

Remainder operation (modulo operation)

  • The remainder operation is also called modulo operation, which is expressed by the percentage sign
  • a%b represents the remainder of a divided by b. It doesn't care about the integer part, only the remainder

(25) , implicit type conversion

If an operand participating in the operation is not numeric, JavaScript will automatically convert the operator to a number

The essence of implicit conversion is to call the Number () function internally
 


 

 

 

Solution: during decimal operation, call the toFixed () method of the number to keep the specified decimal places  

 

(26) , power and open radical

Power calculation is not provided in JavaScript, and the operator with open root sign needs to use the methods related to Math object for calculation

(27) , round up and round down

 

(28) Relation expression  

(29) . judge whether they are equal

  (30) , equality and congruence

 

 

(31) , NaN, etc  

How to judge the value of a variable as NaN?

  • The isNaN() function can be used to determine whether the value of a variable is NaN
  • However, isNaN() is not easy to use. Its mechanism is that as long as the execution result of the variable passed in Number () is NaN, the isNaN() function will get true

 

Inequality and incompleteness

There is no Lianbi in JS

Judge whether the variable a is between 3 and 15. How should I write it?

(32) , non operation

The result of the inverse operation must be a Boolean value

 

(33) , and operation

 

(34) , or operation  

(35) . short circuit calculation  

 

 

 

 

(36) Sequence of logical operations  

(37) , assignment operator  

 

 

 

(38) , shortcut operator

Shortcut operators represent further operations on the basis of the original array

 

(39) , self increasing and self decreasing operators

 

(40) . comprehensive expression

Operation sequence of comprehensive expression: non operation - mathematical operation - relational operation - logical operation

Range representation of variables

Knowledge review

 

function

(1) , function definition and call

(2) . function call

Executing all statements in the function body is called a function call
Calling a function is very simple. You only need to write a pair of parentheses after the function name

(3) . execution order of statements  

 

(4) Promotion of function declaration

Like variable declaration promotion, function declarations can also be promoted

 

The expression of a function cannot be promoted. If a function is defined by the writing method of a function expression, there is no promotion feature  

 

(5) Priority promotion of functions  

 

<script>
        //First, the function will be promoted first
        //After the definition of a variable is promoted, the first promoted will not be overwritten
        //Variable promotion will only promote the definition first, not the value
        fun();
        var fun = function() {
            alert('A');
        }


        function fun() {
            alert('B')
        }

        fun();
    </script>

 

(6) Parameters of function

Parameters are some specific values in the function. When calling the function, you must pass in the specific values of these parameters

The number of parameters of a function. A function can have no parameters or multiple parameters. Multiple parameters should be separated by commas

 

(7) , arguments  

 

  <script>
           function fun() {
            var sum = 0;
            for (var i = 0; i < arguments.length; i++) {
                sum += arguments[i];

            }

            console.log('The sum of all parameters is:' + sum); //110
        }

        fun(33, 22, 55)
    </script>

 

 

(8) Return value of function

In the function body, you can use the return keyword to represent the "return value of the function"

 

   //The function returns the sum of two parameters
        function sum(a, b) {
            return a + b;
        }


        var result = sum(3, 4);
        console.log(result);

 

(9) Return value of function

Calling a function with a return value can be treated as a normal value and can appear anywhere that can be written


 

 

(10) . exit the function when you encounter return

When calling a function, once a return statement is encountered, the function will exit immediately and the execution right will be returned to the caller

1
A
B
2

  Combining if statements often does not need to write else branches

   <script>
        //The function of writing a function is to judge whether a number is even
        function checkEven(n) {
            if (n % 2 == 0) return true;
            return false;
        }

        var result = checkEven(7);
        console.log(result); //false
    </script>

Function is like a small factory  

(11) . exercises  

  <script>
        //Calculate the factorial of a number
        function factorial(n) {
            //Multipliers
            var result = 1;
            for (var i = 1; i <= n; i++) {
                result *= i;

            }
            return result;
        }

        //Exhaustive method
            for (var i = 100; i <= 999; i++) {
            // Change the number i into a string
            var i_str = i.toString();
            var a = Number(i_str[0]);
            var b = Number(i_str[1]);
            var c = Number(i_str[2]);
            // Judging by the number of trumpets
            if (factorial(a) + factorial(b) + factorial(c) == i) {
                console.log(i);//145
            }
        }
    </script>

 

(12) . JavaScript built-in sort() method

A and b in this function represent the front and back items in the array respectively. If they need to be exchanged, they will return a positive number, otherwise they will return a negative number

 

      <script>
        var arr = [3, 5, 6, 1, 2];
        arr.sort(function(a, b) {
            return a - b;
        })

        console.log(arr);


        var arr = [99, 55, 66, 77];
        arr.sort(function(a, b) {
            return b - a;
        })

        console.log(arr);
     </script>

 

(13) What is recursion?
The internal statement of the function can call the function itself to initiate an iteration of the function.

In the new iteration, the statement calling the function itself will be executed, resulting in another iteration. When the function is executed to a certain time, no new iteration will be carried out. The function is returned layer by layer, and the function is recursive

Return is a relatively advanced programming skill, which transforms a large and complex problem layer by layer into a smaller problem similar to the original problem.
 

   <script>
        //Writing a function will call itself to form recursion
        //The function of a function is to calculate a factorial. The factorial of n is the factorial of n*(n-1)
        function factorial(n) {
            //Recursive exit if you calculate the factorial of 1, you can tell you the answer 1 without recursion
            if (n == 1) return 1;
            //If you ask for a factorial other than 1, return n*(n-1)!
            return n * factorial(n - 1);
        }

        var result = factorial(6);
        console.log(result); //720
    </script>

Recursive elements

  • Boundary condition: determines when recursion ends, also known as recursion exit
  • Recursive mode: how big problems are decomposed into small problems, also known as recursive body

Common algorithm problems of recursion

  <script>
        // Write a function whose function is to return the value of the item with subscript n in the Fibonacci sequence

        function fib(n) {
            //The values of the items with a subscript of 0 and a subscript of 1 in the exit sequence are both 1
            if (n == 0 || n == 1) return 1;
            // The essential characteristic of Fibonacci sequence is that each term is equal to the sum of the first two terms
            return fib(n - 1) + fib(n - 2);

        }
        //Write a circular statement to calculate the first 15 items of the Fibonacci sequence
        for (var i = 0; i < 15; i++) {
            console.log(fib(i));
        }
    </script>

 

(14) . deep cloning  

<script>
        //Original array
        var arr1 = [33, 44, 11, 22, [77, 88],
            [11, 999]
        ];
        //Result array "each has a result"
        var result = [];
        //Function this function will be recursive

        function deepClone(arr) {
            //Traverse each item of the array
            for (var i = 0; i < arr.length; i++) {
                //Type judgment if the item traversed is an array
                if (Array.isArray(arr[i])) {
                    //recursion
                    result.push(deepClone(arr[i]));
                } else {
                    //If the item traversed is not an array but a basic type, it is pushed directly into the result array
                    //Equivalent to recursive exit
                    result.push(arr[i])

                }
            }
            //Return result array
            return result;

        }
        //Test it
        var arr2 = deepClone(arr1);
        console.log(arr2);

        //Is it broken
        console.log(arr1[4] == arr2[4]);
        arr1[4].push(99);
        console.log(arr1)
        console.log(arr2);
    </script>

How to implement deep cloning?

Using the idea of recursion, the overall idea is similar to that of shallow cloning, but some changes are made. If the traversed item is a basic type value, it will be directly pushed into the result array. If the traversed item is another array, the shallow cloning operation will be repeated.

  (15) Shallow cloning

  <script>
        //Prepare original array
        var arr1 = [33, 44, 55, 66, [99, 22], 111];
        //Prepare a result array
        var result = [];
        //Traverse the original array
        for (var i = 0; i < arr1.length; i++) {
            result.push(arr1[i]);
        }
        //Output result array
        console.log(result);
        // Test whether cloning is implemented, that is, it is essentially a different array in memory
        console.log(arr1 == result); // false
        //Testing such clones is a shallow clone
        arr1[4].push(100);
        console.log(result);
    </script>

 

(16) , global and local variables

Scope of variable

JavaScript is a function level scoped programming language: variables are meaningful only within the function in which they are defined

 

global variable

If the function is not defined inside any function, this variable is a global variable. It can be accessed and changed within any function

 

 

(17) . shielding effect

Masking effect: if a variable with the same name as the global variable is also defined in the function, the variable in the function will mask the global variable

 

(18) . consider the situation of variable promotion  

 

(19) And formal parameters are also local variables  

 <script>
        var a = 10;

        function fun(a) {
            a++;
            console.log(a); //8
        }

        fun(7);
        console.log(a); //10
    </script>

 

(20) Scope chain

A function can also be defined inside a function. Similar to local variables, the function defined inside a function is a local function

 

Scope chain: in function nesting, a variable will look for its definition layer by layer from inside to outside  

 

 <script>
        var a = 10;
        var b = 20;

        function fun() {
            var c = 30;

            function inner() {
                var a = 40;
                var d = 50;
                console.log(a, b, c, d); //40 20 30 50
            }
            inner();
        }

        fun();
    </script>

Global variables will be defined without var

When assigning a value to a variable for the first time, if var is not added, the global variable will be defined

  <script>
        var a = 1;
        var b = 2;

        function fun() {
            //The letter c has no var keyword, so it is a global variable
            c = 3;
            var b = 4;
            b++;
            c++;
        }
        fun();
        console.log(b); //2
        //The variable c can be accessed outside the function
        console.log(c); //4
    </script>

(21) Closure  

What is a closure: a closure is a combination of the function itself and the environment state in which the function is declared. A function can "remember" the environment in which it is defined. Even if the function is not called in its defined environment, it can access the environment variable in which it is defined  

 

  <script>
        //Create a function
        function fun() {
            //Define local variables
            var name = 'Muke network';
            //Returns a local function
            return function() {
                alert(name)
            }
        }

        //Call the external function to get the internal function
        var inner = fun();
        //Define a global variable
        var name = 'ABC';
        //Executing the inn function is equivalent to executing the internal function outside the fun function
        inner()
    </script>

Observe the phenomenon of closure

In JavaScript, closures are created every time a function is created
However, closures often need to be executed in another place before they can be observed

Use of closures

  • Memory: when a closure is generated, the bad state of the function will always be kept in memory and will not be automatically cleared after the outer function is called. This is the memory of the closure

 

 <script>
        function createCheckTemp(standardTemp) {
            function checkTemp(n) {
                if (n <= standardTemp) {
                    alert("Your temperature is normal")
                } else {
                    alert("Your temperature is on the high side")
                }
            }
            return checkTemp;
        }
        //Create a checkTemp function, which takes 37.1 as the standard line
        var checkTemp_A = createCheckTemp(37.1);
        //Create a checkTemp function, which takes 37.3 as the standard line
        var checkTemp_B = createCheckTemp(37.3);

        checkTemp_A(37.2);
        checkTemp_B(37.2);
    </script>

Purpose of closures - simulate private variables  

 

 <script>
        //Encapsulate a variable. The function of this function is to privatize variables
        function fun() {
            // Define a local variable a
            var a = 0;
            return {
                getA: function() {
                    return a;
                },
                add: function() {
                    a++;
                },
                pow: function() {
                    a *= 2;
                }
            }
        }
        var obj = fun();
        //If you want to use variable a outside the fun function, the only way is to call the getA() method
        console.log(obj.getA());
        //Want a to add one
        obj.add();
        console.log(obj.getA());
        obj.pow();
        console.log(obj.getA());
    </script>

Considerations for using closures

Do not abuse closures, otherwise it will cause performance problems of web pages. In severe cases, it may lead to memory leakage. The so-called memory leakage refers to that the dynamically allocated memory in the program is not released or cannot be released for some reason

 

 <script>
        function addCount() {
            var count = 0;
            return function() {
                count = count + 1;
                console.log(count);
            }
        }

        var fun1 = addCount();
        var fun2 = addCount();
        fun1(); //1
        fun2(); //1
        fun2(); //2
        fun1(); //2
    </script>

(22) , IIFE

IIFE (Immediately Invoked Function Expression) is a special JavaScript function writing method. Once defined, it will be called immediately

Method of forming IIFE

Functions cannot be called directly with parentheses

 

A function must be converted to a function expression to be called

Role of IIFE

Assigning values to variables: when assigning values to variables requires some complex calculations (such as if statements), using IIFE makes the syntax more compact

  IIFE can change global variables into local variables in some situations (such as for loop), and the syntax is more compact

 

(41) . process control statement

Basic use of if statement


 

 

 

       //Three digits are required
        var n = Number(prompt('Please enter three digits'));
        //Validate the value entered by the user
        if (!isNaN(n) && 100 <= n && n <= 999) {
            var a = parseInt(n / 100);
            var b = parseInt(n / 10) % 10;
            var c = n % 10;
            if (Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c, 3)) {
                alert('It's daffodils');
            }
        } else {
            alert('The number you entered is illegal')
        }

(42) . switch statement

Purpose of switch statement: when a variable is classified and discussed

 

 

The switch statement is not like the if statement. When a branch is executed, it will automatically jump out of the if statement. We must actively call the break statement to jump out of the break statement body. If the break is not written, all subsequent case s will be regarded as matches until the break is met  

 

  <script>
        //Let the user enter the month
        var month = Number(prompt('Please enter the month'));
        //Classified discussion
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                alert('There are 31 days in this month');
                break;

            case 4:
            case 6:
            case 9:
            case 11:
                alert('There are 28 days in this month');
                break;

            case 2:
                alert('This month has 28 or 29 days');
                break;
            default:
                alert('The month you entered is incorrect')

        }
    </script>

 

(43) , ternary operator

Purpose of ternary operator: select the value of a variable from two different values according to whether a condition is true or not

 

(44) , for loop  

Execution mechanism of for loop statement  

 

 

Accurately traverse the for loop  

 

 

 

 

  <script>
        //sum is the accumulator, and the initial value is 0
        for (var i = 1, sum = 0; i <= 100; i++) {
            sum += i;
        }
        console.log(sum); //5050
    </script>

 

       //Exhaustive method
        for (var i = 1; i < 100; i++) {
            if (i % 3 == 1 && i % 4 == 2 && i % 5 == 3) {
                console.log(i); //58
            }
        }

 

 

(45) , while loop statement


1. The while statement is also a loop statement, which is an indefinite range of loops. It has different uses from the for loop. Almost all loops provide both for loop and while loop

2. The while statement does not specify the start and end range of the loop in advance. The loop will be executed as long as the test conditions are met

3. The while loop does not show the definition of loop variables. You must first define the loop variables outside the while loop. Sometimes there are even no loop variables

4. The statements in the loop body must make the loop test conditions tend to be invalid, otherwise it will be dead loop
 

 

        var i = 1;
        while (i <= 100) {
            console.log(i);
            i++;
        }
 //Find the smallest integer satisfying that the sum of squares of n is greater than 456789
        //The exhaustive method starts from 1
        var n = 1;
        while (n * n < 456789) {
            n++;
        }

        console.log(n); //676

 

         var n = 1;
        var sum = 0;
        while (sum < 500) {
            sum += n;
            n++;
        }
        //Notice that there is a "make a mistake"
        console.log(n - 1); //32

 

(46) , break, and continue

break means to terminate the loop immediately. It can only be used in loop statements, both in for loops and while loops

 

Continue is used to skip one iteration in the loop and continue to execute the next iteration in the loop. Continue is often used in the for loop

 

  (47) , do while statements

 

  <script>
        //A form of post judgment executes the loop body at least once
        do {
            console.log('★');
        } while (false); //★
    </script>
        var n = 1;
        do {
            console.log(n);
            n++
        } while (n <= 100);

(48) Random number function

The random number function gets a decimal number between 0 and 1

 

 

(49) Small cases of do while  

    <script>
        do {
            var dx = parseInt(Math.random() * 9) - 4;
            var dy = parseInt(Math.random() * 9) - 4;
        }
        while (dx == 0 && dy == 0);
        console.log(dx, dy);
    </script>

(50) Guessing numbers games  

    <script>
        //Random number 2-99
        var answer = parseInt(Math.random() * 98) + 2;
        //At this time, the maximum and minimum values of the range are used to prompt the user
        var min = 1;
        var max = 100;
        //Constant repetition is a dead cycle
        while (true) {
            //Ask the user to guess the number
            var n = Number(prompt('Please guess the number' + min + '~' + max));
            //Verify that the number entered by the user is within the range
            if (n <= min || n >= max) {
                alert('The number you entered is not in the range')
                    //Abandon this loop and start the next iteration
                continue;
            }
            //Judge the relationship between the number entered by the user and the answer
            if (n > answer) {
                alert('The number you entered is too large');
                //Because the number entered by the user is large, the number in the maximum range at this time can be changed into the value entered by the user
                max = n;
            } else if (n < answer) {
                alert('The number you entered is too small')
                    //Because the number entered by the user is small, the number in the minimum range at this time can be changed into the value entered by the user
                min = n;


            } else {
                alert('You guessed right');
                //End dead cycle
                break;
            }
        }
    </script>

 

51. What is an algorithm

  • Algorithm refers to the accurate and complete description of the problem-solving scheme and a series of clear instructions to solve the problem. The algorithm represents the strategy mechanism to describe the problem-solving in a systematic way, that is, it can obtain the required output for a certain standard input in a limited time

  • Algorithm is to decompose a problem into steps that the computer can perform step by step

 

Requirements for excellent algorithms

  • Correctness
  • Robustness
  • Readability

  (52) pseudo code

(53) how to cultivate algorithms

  • Knock more, practice more and summarize more
  • Classic business requirement scenarios should be kept in mind

 

  (54) accumulator

 

        //User input number n
        var n = Number(prompt('please enter a number'));

        //accumulator
        var sum = 0;
        //Ergodic denominator
        for (var i = 2; i <= n; i++) {
            sum += (i + 1) / i
        }

        alert(sum.toFixed(2));

(55) multiplier

  <script>
        //Calculate factorial
        var n = Number(prompt('please enter a number'));
        //The multiplier starts at 1. If you want to multiply 0 by any number from 0, it will be 0
        var result = 1;
        //Inverse ergodic factorial calculation
        for (var i = n; i >= 1; i--) {
            result *= i;
        }

        alert(result);
    </script>

 

(56) exhaustive method

The most outstanding ability of computer is calculation. It has no ability of induction, summary and reasoning logic. Therefore, when people use computer to solve problems, they should develop their strengths and avoid their weaknesses, give full play to the advantages of computer, and don't let them carry out logical reasoning. Exhaustive method is such an algorithm idea.

What is exhaustive method?

Exhaustive method, as the name suggests, refers to determining the approximate range of answers according to the conditions of the question, and verifying all possible situations one by one within this range until all the situations are verified. If a situation meets the conditions of the question, it is a solution to the question. If all the situations do not meet the conditions after verification, there is no solution to the question.

 

     //Exhaustive method
        for (var i = 1; i <= 100; i++) {
            if (i % 3 == 0 && i % 5 == 0) {
                console.log(i);
            }
        }

 

       //Find divisor
        var n = Number(prompt('Please enter a number:'));
        //Exhaustive method
        for (var i = 1; i <= n; i++) {
            if (n % i == 0) {
                console.log(i);
            }
        }

 

      //Looking for daffodils
        for (var i = 100; i < 1000; i++) {
            var i_str = i.toString();
            var a = i_str.charAt(0);
            var b = i_str.charAt(1);
            var c = i_str.charAt(2);
            if (Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c, 3) == i) {
                console.log(i);
            }
        }

(23) Introduction to DOM  

 

(24) Common attributes of, nodeType  

(25) , access element nodes

The so-called access element node means to get the element node on the page

Any operation on the node is to get the node. Accessing the node mainly depends on the document object

Understanding document objects

(26) Common methods for accessing element nodes  

(27) , getElementById ()

  • If there is the same id element on the page, you can only get the first one
  • No matter how deep the element is hidden, it can be found through Id

 

 

Delayed operation

 

 

(28) , getElementsByTagName()

 

 

matters needing attention:

  • The array is easy to traverse, so you can batch manipulate element nodes
  • Even if there is only one node with a specified tag name on the page, an array with a length of 1 is obtained
  • Any node element can also call the getElementsByTagName () method to get some kind of internal element node

 

  (29) , getElementsByClassName()

 

 

(30) , querySelector ()  

 

(31) , querySelectorAll()  

 

(31) Relationship between nodes  

 

 

Text nodes also belong to nodes
In the standard W3C specification, blank text nodes should also be counted as nodes, but there will be some compatibility problems in IE8 and previous nodes. They do not regard empty text nodes as nodes  

 

 

 

(32) . node operation

Two related attributes can be used to change the content in an element node

The innerHTML attribute can set the content in the node in HTML syntax

The innerText property can only set the content in a node in plain text

 

 

 

 

 

 

<body>
    <div id="box">
        <p>I am the original paragraph 0</p>
        <p>I am the original paragraph 1</p>
        <p>I am the original paragraph 2</p>
    </div>
    <script>
        var oBox = document.getElementById('box');
        var oPs = oBox.getElementsByTagName('p');

        //Create orphan node
        var oP = document.createElement('p');
        //Set internal text
        oP.innerHTML = 'I'm new here'
            //Go up the tree
            //oBox.appendChild(oP);
        oBox.insertBefore(oP, oPs[0])
    </script>
</body>

 

 

 

 

 

 

 

 

 <style>
        div {
            width: 200px;
            height: 200px;
            background-color: #ccc;
        }
    </style>
</head>

<body>
    <div id="box">

    </div>
    <script>
        var oBox = document.getElementById('box');
        //Add click event listening to this box
        oBox.onclick = function() {
            alert('Hello, I'm the function of click event');
        }
    </script>

 

 

 

 

 

 

 

 

 

 

 

<script>
        var box1 = document.getElementById("box1");
        var box2 = document.getElementById("box2");
        var box3 = document.getElementById("box3");
        //   box1.onclick = function() {
        //       alert('A');
        //   }
        //   box1.onclick = function() {
        //       alert('B '); //B
        //   }


        box2.addEventListener("click", function() {
            alert('C ');
        }, false)

        box2.addEventListener("click", function() {
            alert('D '); //C before D
        }, false)
    </script>

 

(47) . event object

The event handler function provides a formal parameter, which is an object that encapsulates the details of the event. This parameter is usually represented by the word event or the letter e

(48) . mouse position

 

 

 

  <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        #box {
            width: 200px;
            height: 200px;
            background-color: #333;
            margin: 100px;
            padding: 50px;
        }
        
        body {
            height: 2000px;
        }
        
        #info {
            font-size: 30px;
        }
    </style>
</head>

<body>
    <div id="box">

    </div>
    <div id="info">

    </div>
    <script>
        var oBox = document.getElementById('box');

        var oInfo = document.getElementById('info');

        oBox.onmouseover = function(e) {
            oInfo.innerHTML = 'offsetX / Y: ' +
                e.offsetX + ',' + e.offsetY + '<br/>' + 'clientX/Y:' + e.clientX + ',' + e.clientY;

        }
    </script>

 

 

 

 

 <script>
        var oList = document.getElementById('list');

        var lis = oList.getElementsByTagName('li');

        //  Write circular statements and add listening in batches
        for (var i = 0; i < lis.length; i++) {
            lis[i].onclick = function() {
                this.style.color = ' red';
            }
        }
    </script>

 

 

 

 

 

 

 

 

 

What is a named function? What is an anonymous function?

Named function, so the meaning of name is the function with name. Named function is generally one of the most defined functions

 

// function
function fn() {
    console.log('I'm a named function')
    console.log('Look, I have a name')
    console.log('My name is fn')
}
fn()
fn()

 

Anonymous function

Anonymous functions without names can be seen everywhere. Let's write some anonymous functions

setTimeout(function () {
  console.log('I am an anonymous function. I am used to pass timer parameters')
}, 1000)

let arr = [1, 2, 3]
arr.forEach(function (item) {
  console.log('I am an anonymous function and I am used for callback function parameters')
})

let box = document.querySelector('#box')
box.onclick = function () {
  console.log('I am an anonymous function and I am used to bind events')
}

 

 <h1 id="info"></h1>
    <button id="btn1">start</button>
    <button id="btn2">suspend</button>
    <script>
        var oInfo = document.getElementById('info')
        var btn1 = document.getElementById("btn1");
        var btn2 = document.getElementById("btn2");

        var a = 0;
        //Set a global variable
        var timer;

        btn1.onclick = function() {
            //To prevent timer superposition, we should clear the timer before setting the timer
            clearInterval(timer)
                //Change the value of the global variable to a timer entity
            timer = setInterval(function() {
                oInfo.innerText = ++a;
            }, 1000)
        }

        btn2.onclick = function() {
            clearInterval(timer)
        }
    </script>

 

 <button id="btn1">2 Pop up in seconds hello</button>
    <button id="btn2">2 Cancel pop-up in seconds</button>
    <script>
        var btn1 = document.getElementById("btn1");
        var btn2 = document.getElementById("btn2");

        var timer;
        btn1.onclick = function() {
            timer = setTimeout(function() {
                alert('Hello, world!');
            }, 2000)
        }

        btn2.onclick = function() {
            clearInterval(timer);
        }
    </script>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

(61). BOM special effects development returns to the top  

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            height: 5000px;
            background-image: linear-gradient(to bottom, blue, green, yellow);
        }
        
        .backtotop {
            width: 60px;
            height: 60px;
            background-color: rgba(255, 255, 255, 0.6);
            position: fixed;
            bottom: 100px;
            right: 100px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div class="backtotop" id="backtotopbtn">Back to top</div>
    <script>
        var backtotopbtn = document.getElementById("backtotopbtn");
        var timer;
        backtotopbtn.onclick = function() {
            //Setting table closed first
            clearInterval(timer);
            //set timer 
            timer = setInterval(function() {
                //Reduce scrollTop
                document.documentElement.scrollTop -= 80;
                // The timer stops
                if (document.documentElement.scrollTop <= 10) {
                    clearInterval(timer);
                }
            }, 20)
        }
    </script>
</body>

</html>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Recommended reading:

JS uses recursion to traverse the array and filter the required data

20 killer JavaScript single line code

Write JavaScript code gracefully

Posted by alimadzi on Sat, 16 Oct 2021 00:30:06 -0700