The fourth day of learning JSDOM and BOM

Posted by anthony522 on Sat, 26 Feb 2022 08:07:25 +0100

js DOM and BOM study day 4

1. BOM overview

1.1 what is BOM

  • BOM (Browser Object Model), Browser Object Model, which provides content independent objects that interact with browser windows. The core object is window
  • BOM consists of a series of objects with multiple attributes and methods
  • BOM lacks standards. js standard ECMA, DOM standard W3C, BOM was originally NetScape browser standard

graphic

BOM structure diagram

1.2 composition of BOM

  • The window object is the top-level object of the browser
    1. It is an interface for js to access the browser
    2. It is a global object in which variables and functions defined become its properties and methods
  • Window has a special attribute: window Name, which is empty by default

Examples

<!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>
</head>
<body>
    <script>
        // 1. Top level object window

        window.alert(11);
        alert(11);
        console.log(window.name);
        function f1(){
            console.log(12);
        }

        f1();
        window.f1();
    </script>
</body>
</html>
  • design sketch

2. Common events of window objects

2.1 window loading events

window.οnlοad=function(){}
window.addEventListener('load',function(){})
  • When the window contents (css style sheets, pictures, script files, etc.) are all loaded, the processing function is executed
  • With this, you can write the js code above the page elements
  • The traditional writing method is based on the last one, and the listener method can write multiple

2.1.2 window loading events more commonly used in development

document.addEventListener('DOMContentLoaded',function(){})
  • When the HTML elements are loaded (excluding pictures and style sheets), the processing functions are executed to improve the user experience

Examples

<!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>
    <script>
        // 1. Raise the window loading event so that the script file is placed in front of the element
        window.addEventListener('load',function(){
            alert('555');
        })


        // 
        window.addEventListener('load',function(){
            var btn=document.querySelector('button');
            btn.onclick=function(){
            alert('666')
        }
        })

        // DOM page loading completed (html element loading completed)
        window.addEventListener('DOMContentLoaded',function(){
            alert('777');
        })
        
    </script>
</head>
<body>
    <button>Button</button>
</body>
</html>
  • design sketch

2.2 window resizing events

window.οnresize=function(){};
window.addEventListener('resize',function(){})
  • The event is triggered when the window size changes
  • window.innerWidth the width of the current screen

Examples

<!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>
        div{
            width: 200px;
            height: 200px;
            background-color: pink;
        }
    </style>
    <script>
        window.addEventListener('load',function(){
            var div=document.querySelector('div');
            // If the current window width is less than 900px, hide the pink box
            window.addEventListener('resize',function(){
                if(window.innerWidth<='900'){
                    div.style.display='none';
                }else{
                    div.style.display='block';
                }
            })
        })
    </script>
</head>
<body>
    <div class="box">

    </div>
</body>
</html>
  • design sketch

3. Timer (method of window object)

3.1 setTimeout timer

window.setTimeout(The number of milliseconds to delay when calling a function (the default is 0))
  • After the delay of milliseconds, execute the calling function and call it once

Attention

  • window can be omitted, object method
  • Three forms of calling function (anonymous function, function name, 'function name ()')
  • Timer recommended name

Examples

<!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>
</head>
<body>
    <script>
        // 1.setTimeout timer
        // window can be omitted
        var timer1=setTimeout(function(){
            alert(666);
        },2000);

        // It is recommended to name the timer

        function f1(){
            alert('777');
        }

        // The second way to write a calling function
        var timer2=setTimeout(f1,5000);
    </script>
</body>
</html>
  • design sketch

Callback function

  • This function is called callback function when the time is up
  • For example, timer, mouse click event, keyboard event and window loading event, their processing functions will not be executed until a certain time
Examples
<!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>
</head>
<body>
    <img src="./images/ad.jpg" alt="">

    <script>
        // 1. Make the picture hide automatically after 5 seconds
        var img=document.querySelector('img');
        setTimeout(function(){
            img.style.display='none';
        },5000)
    </script>
</body>
</html>
  • design sketch

3.2 stop timer

window.clearTimeout(Name of timer)
  • Clear the specified timer, and the window can be omitted

Examples

<!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>
</head>
<body>
    <button>Stop timer</button>
    <script>
        // 1. Set timer
        var timer=setTimeout(function(){
            alert(888)
        },5000);

        // 2. Stop timer
        var btn=document.querySelector('button');
        btn.addEventListener('click',function(){
            clearTimeout(timer);
        })
        
    </script>
</body>
</html>
  • design sketch

3.3 setInterval timer

window.setInterval(Callback function, number of milliseconds between)
  • Call a function repeatedly, and call the callback function every other time

Examples

<!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>
</head>
<body>
    <script>
        // setInterval timer
        setInterval(function(){
            console.log(100);
        },2000)
    </script>
</body>
</html>
  • design sketch

Countdown case

<!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>

        *{
            padding: 0;
            margin: 0;
        }
        .box div{
            margin:15px;
            float: left;
            width: 100px;
            height: 100px;
            background-color: #000;
            color: #fff;
            font-size: 40px;
            text-align: center;
            line-height: 100px;
        }

        .box {
            width: 600px;
            margin: 100px auto;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="hour">1</div>
        <div class="minute">2</div>
        <div class="second">3</div>
    </div>


    <script>

        var inputTime=+new Date('2022-2-20 23:00');//Returns the total number of milliseconds of user input time
        var hour=document.querySelector('.hour');
        var minute=document.querySelector('.minute');
        var second=document.querySelector('.second');

        // Execute once first
        countDown();
        // Set a timer

        setInterval(countDown,1000)

        function countDown(){
            var nowtime=+new Date();
            
            var restTime=(inputTime-nowtime)/1000;

            var s=parseInt(restTime%60);
            // Pre zero
            s=s<10? '0'+s:s;
            second.innerHTML=s;
            var m=parseInt(restTime/60%60);
            m=m<10? '0'+m:m;
            minute.innerHTML=m;
            var h=parseInt(restTime/60/60%24);
            h=h<10? '0'+h:h;
            hour.innerHTML=h;
            
        }
    </script>
</body>
</html>
  • design sketch

3.4 stop setInterval timer

window.clearInterval(intervalID)
  • Cancels the timer previously established by calling setInterval()
  • window can be omitted

Examples

<!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>
</head>
<body>
    <button>Start timer</button>
    <button>Stop Timer </button>
    <script>
        var begin=document.querySelector('button');
        var stop=begin.nextElementSibling;
        var timer=null;
        begin.onclick=function(){
            timer=setInterval(function(){
                console.log('output');
            },1000)
        }

        stop.onclick=function(){
            clearInterval(timer)
        }
    </script>
</body>
</html>
  • design sketch

3.5 this pointing

  • This in the global scope and ordinary functions points to the top-level object window (this in the timer is also window, and the timer is also the method of window object)
  • When a method is called, who calls the method and points to whom
  • this in the constructor points to the instance object of the constructor

Examples

<!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>
</head>
<body>
    <button>Button</button>
    <script>
        // 1. Under the global scope and the common function this point
        console.log(this);

        function fn1(){
            console.log(this);
        }

        fn1();

        // 2. Method caller

        var o={

            sayhi:function(){
                console.log(this);
            }
        }

        o.sayhi();

        var btn=document.querySelector('button');
        btn.onclick=function(){
            console.log(this);
        }


        // 3. this point of constructor
        function Fan(){
            console.log(this);
        }

        var fun=new Fan();
    </script>
</body>
</html>
  • design sketch

4.js execution mechanism

4.1 js execution mechanism is single thread

  • You can only do one thing at a time

4.2 synchronous and asynchronous

  • HTML5 proposes a web worker standard that allows js to create multithreads
  • Synchronization: perform the next task after the previous task is completed
  • Asynchronous: you can handle other events while doing this

Examples

<!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>
</head>
<body>
    <script>
        // Due to the standard proposed by h5, the process code will be executed asynchronously
        console.log(1);
        setTimeout(function(){
            console.log(3);
        },3000)
        console.log(2);
    </script>
</body>
</html>
  • design sketch

4.3 synchronous and asynchronous tasks

  • Synchronization task

    • Synchronization tasks are executed on the main thread to form an execution stack
  • Asynchronous task

    • The asynchrony of js is realized through callback function
  • Type of asynchronous task

    1. Common events: click, resize
    2. Loading event: load, error
    3. Timers: setInterval, setTimeout
  • The callback functions related to asynchronous tasks are added to the task queue (message queue)

  • graphic

4.4 js execution mechanism

  1. Execute the synchronization task in the stack first
  2. When a synchronization task with callback function is encountered, put the callback function into the message queue
  3. Continue the synchronization task in the stack
  4. When all synchronous tasks in the execution stack are completed, go to the message queue to execute asynchronous tasks

Examples

<!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>
</head>
<body>
    <script>
        // According to the task execution mechanism, 1, 2 and 3 are obtained
        console.log(1);
        setTimeout(function(){
            console.log(3);
        },0);
        console.log(2);
    </script>
</body>
</html>
  • design sketch

graphic

  • The main thread repeatedly obtains and executes tasks, and then obtains and executes tasks. This mechanism is called event loop
An instance
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>

        // Check whether there is a circular execution queue in the task stack, and check whether there is a circular execution queue in the task stack
        console.log(1);
        document.onclick=function(){
            console.log('click');
        }

        console.log(2);

        setTimeout(function(){
            console.log('timeout');
        },3000)
    </script>
</body>
</html>
  • design sketch

5.location object

5.1 what is a location object

  • A property provided by the window object
  • Get or set the url of the form. You can parse the url and return an object

5.2 URL

  • Uniform resource locator

  • The information contained indicates the location of the file and how the browser should handle it

  • General syntax format

    protocol://host[:port]/path/[?query]#fragment
    http://www.itcast.cn/index.html?name=andy&age=18#link
    
    • [] package content optional
  • form

formexplain
protocolcommunication protocol
hostHost (domain name)
portPort number, http, default port 80, can be omitted
pathA string whose path is separated by zero or more '/', indicating a directory or file address on the host
queryOptional parameters, in the form of key value pairs, separated by an & sign
fragmentWhat's # behind the clip is often used to link anchors

5.3 properties of location object

  • The location attribute provided by window returns a location object
  • Object properties
location object propertiesReturn value
location.hrefGets or sets the entire URL
location.hostGet host (domain name)
location.portGets the port number. If it is not written, an empty string is returned
location.pathnameGet pathname
location.searchGet parameters
location.hashReturn the fragment, # following content

Examples

Case of page Jump after 5s

<!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>
</head>
<body>
    <div>
        
    </div>

    <script>
        var div=document.querySelector('div');
        var cnt=5;
        f1();
        // Jump to Baidu home page after 5s
        setInterval(f1,1000)

        function f1(){
            if(cnt===0){
                location.href='https://www.baidu.com/';
            }else{
                div.innerHTML='also'+ cnt+'s Then jump to the home page';
                cnt--;
            }
        }
    </script>
</body>
</html>
  • design sketch

Information transfer between pages

  • Login page
<!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>
</head>
<body>
    <form action="index.html">
        <input type="text" name="uname">
        <button type="submit">Sign in</button>
    </form>
</body>
</html>
  • home page
<!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>
</head>
<body>
    <div>

    </div>

    <script>
        // 1. Get the parameters from login
        var info=location.search;
        // console.log(info);
        // 2. Remove the question mark in uname
        // Start with subscript 1 and take the second parameter to the end without writing
        var sub=info.substr(1);
        // Separating strings into key value pairs
        var arr=sub.split('=');

        // Get value to div

        var div=document.querySelector('div');
        div.innerHTML=arr[1]+'Welcome';
        
    </script>
</body>
</html>
  • design sketch

5.4 method of location object

location object methodReturn value
location.assign()Like href, you can jump to the page (redirect the page) and go back
location.replace()Replace the current page, cannot go back
location.reroad()Reload the page, relative to refresh. If the parameter is true, it is forced to refresh relative to ctrl+f5

Examples

<!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>
</head>
<body>
    <button>Button</button>
    <script>
        var btn=document.querySelector('button');
        btn.addEventListener('click',function(){
            // 1. Jump to a new page and go back
            // location.assign('https://www.baidu.com/');
            // 2. Replace the current page and do not go back
            // location.replace('https://www.baidu.com/');
            // 3. Refresh the page
            location.reload();
        })
    </script>
</body>
</html>
  • assign renderings

  • replace rendering

  • reload renderings

6. navigator object

  • Contains information about the browser. It consists of many properties, the most commonly used: userAgent, which returns the value of the user agent header sent by the client to the server
  • The following front-end code can judge which terminal of the user is opened to realize jump

7.history object

  • Object provided by window
  • Interact with browser history, which contains URL s that users have visited (in browser windows)
history object methodeffect
back()Can reverse function
forword()Forward function
Go (parameter)Forward and backward function, if it is 1, forward 1 step, and - 1, backward one step

Examples

  • home page

    <!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>
    </head>
    <body>
        <a href="./list.html">Go to the list page</a>
        <button>forward</button>
        <script>
            var btn=document.querySelector('button');
            btn.onclick=function(){
                history.forward();
            }
        </script>
    </body>
    </html>
    
  • List page

    <!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>
    </head>
    <body>
        <a href="./index.html">Back to the home page</a>
        <button>Back off</button>
        <script>
            var btn=document.querySelector('button');
            btn.onclick=function(){
                history.back();
            }
        </script>
    </body>
    </html>
    
  • design sketch

8. Homework after class

1. Electronic clock

<!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>
        div{
            width: 400px;
            font-size: 20px;
            margin: 100px auto;
            background-color: skyblue;
            text-align: center;
            
        }
    </style>
</head>
<body>
    <div></div>
    <script>

        function getCurTime(){
            var date=new Date();
            console.log(date);

            var year=date.getFullYear();
            var month=date.getMonth();
            var dates=date.getDate();
            var hour=date.getHours();
            hour=hour<10 ? '0'+hour : hour;
            var minute=date.getMinutes();
            minute=minute<10 ? '0'+minute : minute;
            var second=date.getSeconds();
            second=second<10 ? '0'+second : second;
            var day=date.getDay();
            var days=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
            return year+'year'+month+'month'+dates+'day'+days[day]+' '+hour+':'+minute+':'+second;
        }

        var div=document.querySelector('div');
        div.innerHTML=getCurTime();
        setInterval(function(){
            div.innerHTML=getCurTime();
        },1000)

        
    </script>
</body>
</html>
  • design sketch

2. Countdown to singles day

<!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>

        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .box{
            width: 500px;
            margin: 100px auto;
            /* background-color: pink; */
            text-align: center;
        }

        .box h2{
            margin-bottom: 30px;
        }

        .box span{
            display: inline-block;
            text-align: center;
            height: 30px;
            width: 60px;
            line-height: 30px;
        }

        .box span:nth-of-type(1){
            color: orange;
        }

        .box span:nth-of-type(n+2){
            color: #fff;
            background-color: orange;
            
        }
    </style>
</head>
<body>
    <div class="box">
        <h2>From singles day, and</h2>
        <span>1</span>
        <span>2</span>
        <span>3</span>
        <span>4</span>
    </div>

    <script>
        var iptTime=new Date('2022-11-11 00:00:00');
        var rDay=document.querySelector('span');
        var rHour=rDay.nextElementSibling;
        var rminute=rHour.nextElementSibling;
        var rsecond=rminute.nextElementSibling;
        getCntTime();
        setInterval(getCntTime,1000);
        function getCntTime(){
            var nowTime=new Date();
            var restTime=(iptTime-nowTime)/1000;
            var s=parseInt(restTime%60);
            s=s<10? '0'+s:s;
            rsecond.innerHTML=s+'second';
            var m=parseInt(restTime/60%60);
            m=m<10? '0'+m:m;
            rminute.innerHTML=m+'branch';
            var h=parseInt(restTime/60/60%24);
            h=h<10? '0'+h:h;
            rHour.innerHTML=h+'Time';
            var day=parseInt(restTime/60/60/24);
            rDay.innerHTML=day+'day';
        }
    </script>
</body>
</html>
  • design sketch

Topics: Javascript Front-end