Front-end JS articles (10) - BOM overview & timer & JS execution mechanism & location & navigator & history

BOM Browser Object Model

After studying in this section, I hope you can master

Be able to tell what is the BOM
Ability to know the browser's top-level object window
Ability to write out page load events and caveats
Be able to write two timer functions and tell the difference
Be able to tell the JS execution mechanism
Can use the location object to complete the jump between pages
Be able to know the attributes involved in the navigator object
Can use history to provide a method to achieve page refresh

1. BOM overview

1.1 What is BOM

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-VQsHhCee-1668340396033)(Typora_image/431.png)]

DOM mainly includes hiding or displaying an element, changing the style and content of an element

BOM mainly includes page bar scrolling, page refresh, page jump

1.2 Composition of BOM

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-XBPZSs0x-1668340396035)(Typora_image/432.png)]

Create a new .html file and execute the code as follows

<!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.window对象是浏览器的顶级对象
        // 之前写的 
        // document.querySelector()
        // 实际完整写法是
        // window.document.querySelector()
        // 2.window是一个全局对象,定义在全局作用域的变量函数都会变成window的属性和方法
        var num = 10;     // 此时它实际就是一个window的属性
        console.log(num);    // 10
        // 实际完整的写法
        console.log(window.num);  // 10

        // 定义一个函数,此时它就会变成window的方法
        function fn() {
            console.log(11);
        }
        // 以前的写法
        fn();   // 11
        // 实际完整的写法
        window.fn();   // 10
        // 3.在调用的时候可以省略window,之前学的alert(),prompt()都是window的对象方法
        // alert(123);
        // window.alert(123); //完整的写法

        // 4.之前为什么不用name做变量名的原因   var name = 10; 不建议这样的写法
        // 原因:
        // 4-1 打印window
        console.log(window);
        // 4-2 因为window有个特殊的属性name
        console.log(window.name);   // 空的字符串


    </script>
</body>
</html>

The effect is as follows

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-JtGyvVfi-1668340396038)(Typora_image/433.png)]

2. Common events of window object

2.1 Window loading event

(With this, the written script can be placed anywhere in the html)

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-D5ju0YfR-1668340396039)(Typora_image/434.png)]

There is also a window load event

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-b2ucuRJM-1668340396040)(Typora_image/437.png)]

Create a new .html file and execute the code as follows

<!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>
        // window.onload = function() {
        //     var btn = document.querySelector('button');
        //     btn.addEventListener('click',function() {
        //     alert('弹出对话框');
        // })
        // }
        // window.onload = function() {
        //     var btn = document.querySelector('button');
        //     btn.addEventListener('click',function() {
        //     alert('弹出对话框222');
        // })
        // }
        // 推荐写法
        window.addEventListener('load', function() {
            var btn = document.querySelector('button');
        btn.addEventListener('click',function() {
            alert('11');
        })
        })
        window.addEventListener('load', function() {
            alert('22');
        })
        document.addEventListener('DOMContentLoaded',function() {
            alert(33);
        })
        // 让JS可以放到页面任何一个位置,可以用页面加载事件来处理
        // 这两种页面加载事件的区别
        // load 等页面内容全部加载完毕,包含页面dom元素 图片 flash css等
        // DOMContentLoaded 是DOM 加载完毕,不包含图片 falsh css 等就可以执行 加载速度比load更快一些 (适用图片比较多的页面)
    </script>
</head>
<body>
    <button>点击</button>
    <!-- <script>
        // 需求:点击按钮,弹出弹窗
        var btn = document.querySelector('button');
        btn.addEventListener('click',function() {
            alert('弹出对话框');
        })
    </script> -->

    <!-- window.onload传统注册事件只能写一次,如果有多个,会以最后一个window.onload为准 -->
</body>
</html>

The effect is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-StLfhi1d-1668340396042)(Typora_image/435.png)]

The effect is as follows

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-op0HKrQ6-1668340396043)(Typora_image/436.png)]

The effect is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-cCHWtSeU-1668340396044)(Typora_image/438.png)]

2.2 Resize window event

(an event that fires when the browser size changes)

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-NSJUb8SC-1668340396045)(Typora_image/439.png)]

Create a new .html file and execute the code as follows

<!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: aquamarine;
        }
    </style>
</head>
<body>
    <!-- 1.当div写上面时 -->
    <!-- <div></div>
    <script>
        // 需求:让盒子小于900px的时候隐藏
        var div = document.querySelector('div')
        window.addEventListener('resize',function() {
            // 获取此时屏幕的宽度
            console.log(window.innerWidth);
            if (window.innerWidth <= 800) {
                div.style.display='none';

            }
        })
    </script> -->

    <script>
        // 当div写任意位置时,完成上面需求
        window.addEventListener('load',function() {
            var div = document.querySelector('div')
            window.addEventListener('resize',function() {
                // 获取此时屏幕的宽度
                console.log(window.innerWidth);
                if (window.innerWidth <= 800) {
                    div.style.display='none';
                } else {
                    div.style.display = 'block';
                }
            })
        })

    </script>
    <div></div>
</body>
</html>

The effect is as follows

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-QkPzXD43-1668340396046)(Typora_image/440.png)]

3. Timer

The window object provides us with two very useful methods - timers.

setTimeout()
setlnterval()

3.1 setTimeout() timer

window.setTimeout(调用函数,[延迟的毫秒数]);

The setTimeout() method is used to set a timer that executes the calling function after the timer expires.

Notice:

1.window can be omitted

2. The calling function can directly write the function, or write the function name or use the string 'function name ()' in three forms. The third is not recommended

3. If the number of milliseconds of the delay is omitted, the default is 0. If it is written, it must be milliseconds.

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

Create a new .html file and execute the code as follows

<!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
        // 语法规范: window.setTimeout(调用函数,延时时间);
        // 1. 这个windows在调用的时候可以省略
        // 2. 这个延时时间单位是毫秒 但是可以省略  如何省略,默认是0
        setTimeout(function() {
            console.log('2秒后,时间到了');

        },2000)
        // 3.这个调用函数可以直接写函数,还可以写  函数名
        function callback() {
            console.log('该吃饭了');
        }
        setTimeout(callback,3000)
        // 4.这个调用函数还有一个写法 '函数名()'    不提倡这个写法
        // setTimeout('callback()',8000)

        // 5.页面中可能有很多的定时器,我们经常给定时器加标识符 (名字)
        function liv() {
            console.log('3秒后页面跳转');
        }
        var time1 = setTimeout(liv,3000)
        var time2 = setTimeout(liv,5000)
        

    </script>
</body>
</html>

The effect is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-hdWVTzMO-1668340396047)(Typora_image/441.png)]

In the example above

The function setTimeout() is also called the callback function callback

Ordinary functions are called directly in code order.

And this function needs to wait for time, and then call this function when the time is up, so it is called a callback function.

Simple understanding: Callback means calling back. After the last task is done, return to cast and call this function again.

以前我们讲的 element.onclick=function() {} 或者 element.addEventListener("click",fn);里面的函数也是回调函数

3.2 Case: an advertisement that closes automatically in 5 seconds

analyze:

1. Core idea: After 5 seconds, hide the advertisement

2. Use timer setTimeout

Create a new .html file and execute the code as follows

<!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>
        img {
            width: 400px;
            height: 400px;
        }
    </style>
</head>
<body>
    <img src="images/1.jpg" alt="" class="ad">
    <script>
        var ad = document.querySelector('.ad');
        setTimeout(function() {
            ad.style.display = 'none';
        },5000)
    </script>
</body>
</html>

The effect is as follows

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-ZxeKslrz-1668340396048)(Typora_image/442.png)]

3.3 Stop setTimeout() timer

window.clearTimeout(timeoutID);

The clearTimeout() method cancels a timer previously established by calling setTimeout().

Notice:

1.window can be omitted.

2. The parameter inside is the identifier of the timer.

Create a new .html file and execute the code as follows

<!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>
    <script>
        var btn = document.querySelector('button');
        var timer = setTimeout(function() {
            console.log('五秒之后爆炸了');
        },5000);
        btn.addEventListener('click',function() {
            clearTimeout(timer);

        })
    </script>
    
</body>
</html>

The effect is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-cqWFqsFk-1668340396049)(Typora_image/443.png)]

3.4 setInterval() timer

window.setInterval(回调函数,[间隔的毫秒数]);

The setInterval() method calls a function repeatedly, and calls the callback function every once in a while

Notice:

1. window can be omitted

2. The calling function can directly write the function, or write the function name or use the string 'function name ()' in three forms.

3. If the number of milliseconds in the interval is omitted, the default is 0. If it is written, it must be milliseconds, which means that this function will be called automatically every milliseconds.

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

Create a new .html file and execute the code as follows

<!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.setInerval
        // 语法规范:window.setInterval(调用函数,延时时间);
        setInterval(function() {
            console.log('持续输出');
        },1000);

        /* 
        setTimeout和setInterval的区别
        1.setTimeout 延时时间到了,就去调用这个回调函数,只调用一次,就结束了这个定时器
        2.setInterval  每隔这个延时时间,就去调用这个回调函数,会调用很多次,重复调用这个函数       
        */

    </script>
</body>
</html>

The effect is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Dr2ELisN-1668340396050)(Typora_image/444.png)]

3.5 Case: Countdown

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Has3dhMA-1668340396050)(Typora_image/445.png)]

Create a new .html file and execute the code as follows

<!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 {
                background-color: black;
                width: 200px;
                height: 200px;
                margin-left: 20px;
                float: left;
                color: white;
                font-size: 20px;
                text-align: center;
                line-height: 200px;
            }
    </style>
</head>
<body>
    <!-- div>span*3 -->
    <div>
        <span class="hour">1</span>
        <span class="minute">2</span>
        <span class="second">3</span></div>
        <script>
            // 1.获取元素
            var hour = document.querySelector('.hour');    // 小时的黑色盒子
            var minute = document.querySelector('.minute');    // 分钟的黑色盒子
            var second = document.querySelector('.second');    // 秒数的黑色盒子

            


            var inputTime =+ new Date('2022-11-13 00:00:00');    // 返回的是用户输入时间总的毫秒数
            // 3.先调用一次这个函数,防止第一次刷新页面有空白
            countDown();
            
            
            // 2.开启定时器   每隔一秒调用
            setInterval(countDown,1000);

            function countDown() {
                var nowTime = +new Date();
               
                var times = (inputTime - nowTime) / 1000;
                var h = parseInt(times /60 /60 % 24);  // 时
                h = h < 10 ? '0' + h : h;
                hour.innerHTML = h;   // 把剩余的小时   给小时的 黑色盒子
                var m = parseInt(times / 60 % 60);    // 分
                m = m < 10 ? '0' + m : m;
                minute.innerHTML = m;    // 把剩余的分钟 给分钟的 黑色盒子
                var s = parseInt(times % 60);    // 当前的秒
                s = s < 10 ? '0' + s : s;
                second.innerHTML = s;    // 把剩余的秒 给秒的  黑色盒子
            }

        </script>
</body>
</html>

The effect is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-My8mZphu-1668340396051)(Typora_image/446.png)]

3.6 Stop setInterval() timer

window.clearInterval(intervalID);

The clearInterval() method cancels a timer previously established by calling setIntervla().

Notice:

1. The window can be omitted.

2. The parameter inside is the identifier of the timer.

Create a new .html file and execute the code as follows

<!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.begin -->
    <button class="begin">开启定时器</button>
    <button class="stop">停止定时器</button>
    <script>
        var begin = document.querySelector('.begin');
        var stop = document.querySelector('.stop');

        /* begin.addEventListener('click',function() {
            var timer = setInterval(function() {
                console.log('持续发出消息');
            },1000);
        })
        stop.addEventListener('click',function() {
            clearInterval(timer);
        }) 
        这个代码会报错,因为此时begin里面的timer是局部变量,clearInterval()不能调用
        */
       var timer = null;   // 定义一个全局变量   null 是一个空对象
        begin.addEventListener('click',function() {
            timer = setInterval(function() {
                console.log('持续发出消息');
            },1000);
        })
        stop.addEventListener('click',function() {
            clearInterval(timer);
        }) 
    </script>
    
</body>
</html>

The effect is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-pmDQEoAQ-1668340396052)(Typora_image/447.png)]

3.7 Case: Send SMS

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-CDr39Z93-1668340396053)(Typora_image/448.png)]

Create a new .html file and execute the code as follows

<!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>
    手机号码:  <input type="number"> <button>发送</button>
    <script>
        // 1.获取元素
        var btn = document.querySelector('button');

        var time = 3;  // 定义剩下的秒数  全局变量

        btn.addEventListener('click',function() {
            btn.disabled = true;
            // 注意button的特殊之处,用innerHTML来修改内容
            // 例如:btn.innerHTML = '还剩下10秒';
            var timer = setInterval(function() {
                if (time == 0) {
                    // 清除定时器和复原按钮
                    clearInterval(timer);
                    // 启用按钮
                    btn.disabled = false;
                    // 修改文字
                    btn.innerHTML = '发送';
                    // 复原原来的到时间初始时间    这个3需要重新开始
                    time = 3;
                } else {
                    btn.innerHTML = '还剩下' + time + '秒';
                    time --;
                }
            
            },1000);






        })
    </script>
</body>
</html>

The effect is as follows

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-IqwsvCNo-1668340396054)(Typora_image/449.png)]

3.8 this

The point of this cannot be determined when the function is defined. Only when the function is executed can it be determined who this points to. In general, the final point of this is the object that called it.

1. In the global scope or ordinary functions, this points to the global object window (note that this in the timer points to window)

2. Who calls this in the method call and points to whom

3. In the constructor, this points to the instance of the constructor

Create a new .html file and execute the code as follows

<!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>
    <script>
        // this 指向问题  一般情况下this最终指向的是那个调用它的对象

        // 1.全局作用域或者普通函数中this指向全局对象window  (注意定时器里面的this指向window)

        console.log(this);               // window

        function fn() {
            console.log(this);          // window
        }
        fn();
        // 实际fn()全写是  window.fn()
        setTimeout(function() {
            console.log(this);        // window
        },1000);
        // 因为定时器是简写的,全称是 window.setTimeout(function() {},1000);
        // 2.方法调用中谁调用this指向谁
        var o = {
            sayHi:function() {
                console.log(this);        // this指向的是 o 这个对象
            }
        }
        o.sayHi();


        // 点击按钮,查看this的指向
        var btn = document.querySelector('button');
        // btn.onclick = function() {
        //     console.log(this);      //  当点击按钮后,this指向button按钮对象
        // }

        btn.addEventListener('click',function() {
            console.log(this);      // 当点击按钮后,this指向button按钮对象
        })

        // 3.构造函数中this指向构造函数的实例
        function Fun() {
            console.log(this);     // this指向的是fun 实例对象
        }
        var fun = new Fun()     // new会创建新空间,fun指向了这个新空间
        
    </script>
</body>
</html>

The effect is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-vnoelC06-1668340396055)(Typora_image/450.png)]

Through the study of this, you can talk about code optimization for sending SMS

<!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>
    手机号码:  <input type="number"> <button>发送</button>
    <script>
        var btn = document.querySelector('button');
        var time = 3;  
        btn.addEventListener('click',function() {
            this.disabled = true;     // 这里可以把btn替换成this,this指向函数调用,就是btn
            var timer = setInterval(function() {
                if (time == 0) {
                    clearInterval(timer);
                    btn.disabled = false;  // 这里的btn不能改成this,因为这句话在定时器里,定时器里面的指向window
                    btn.innerHTML = '发送';
                    time = 3;
                } else {
                    btn.innerHTML = '还剩下' + time + '秒';
                    time --;
                }         
            },1000);
        })
    </script>
</body>
</html>

4. JS Execution Mechanism

4.1 JS is single-threaded

A major feature of the JavaScript language is single-threaded, that is, only one thing can be done at the same time. This is because of the mission of the birth of JavaScript, a scripting language-JavaScript was born for user interaction on the page and for manipulating the DOM. For example, we can add and delete a certain DOM element, not at the same time. It should be added first and removed later.

Single thread means that all tasks need to be queued, and the next task will be executed only after the previous task is completed. The problem caused by this is: if the execution time of JS is too long, the rendering of the page will be incoherent, resulting in the feeling of page rendering and loading blocking.

4.2 Problems faced

<script>
    console.log(1);
    setTimeout(function() {
        console.log(3);
    },100000);
    console.log(2);
</script>

4.3 Synchronous and asynchronous

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

Synchronize

After the previous task is completed, the next task is executed, and the execution order of the program is consistent with the arrangement order of the tasks. For example: the synchronous method of cooking: we need to boil water to cook rice, wait for the water to boil (after 10 minutes), and then cut and stir-fry vegetables.

asynchronous

When doing one thing, because this thing will take a long time, while doing this thing, you can also deal with other things. For example, the asynchronous method of cooking, we use these 10 minutes to chop and stir-fry vegetables while boiling water.

The essential difference between synchronous and asynchronous: the execution order of each process on this pipeline is different.

[Reminder] Although JS is a single-threaded language, it allows multiple tasks to be created

Create a new .html file and execute the code as follows

<!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>
        console.log(1);
        setTimeout(function() {
            console.log(3);
        },1000);
        console.log(2); 
    </script>
</body>
</html>

The effect is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Eui6qqLo-1668340396055)(Typora_image/451.png)]

4.4 Synchronous task and asynchronous task execution process

What is the final result of the following code?

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

The execution results are as follows

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-JEiKzQNu-1668340396059)(Typora_image/452.png)]

Synchronous tasks and asynchronous tasks

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-I2IOkM6g-1668340396067)(Typora_image/453.png)]

4.5 Execution mechanism of JS

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-hm12ojXx-1668340396069)(Typora_image/454.png)]

Execution mechanism of JS - when performing multitasking

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-flcg8fVq-1668340396070)(Typora_image/455.png)]

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-eEdvj59E-1668340396071)(Typora_image/456.png)]

Create a new .html file and execute the code as follows

<!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>
        console.log(1);
        document.onclick = function() {
            console.log('click');
        }

        console.log(2);

        setTimeout(function() {
            console.log(3);
        },3000)

        /* 
        先执行同步任务,当点击之前没发生时,会先让异步进程进行处理,点击之后才会放到异步任务里面
        当执行定时任务时,会先让异步进程进行处理,当过了三秒之后,才会放到异步任务里面
        
        */
    </script>
</body>
</html>

The effect is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-6P3cgC8b-1668340396072)(Typora_image/457.png)]

5. location object

5.1 What is the location object

The window object provides us with a location property for getting or setting the form URL, and can be used to parse the URL. Because this property returns an object, we also refer to this property as the location object.

5.2 URL

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-E7JjYb1j-1668340396075)(Typora_image/458.png)]

[Reminder] href and search are more important

5.3 Properties of the location object

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-TRsDLjgC-1668340396077)(Typora_image/459.png)]

5.4 Case: Jump to the page after 5 seconds

Create a new .html file and execute the code as follows

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

    <script>
        // 需求:5秒之后跳转页面
        var btn = document.querySelector('button');
        var div = document.querySelector('div');
        // btn.addEventListener('click',function() {
        //     // console.log(window.location.href);  window可以省略
        //     // console.log(location.href);
        //     location.href = 'https://www.jd.com/';
        // })
        var timer = 5;
        // setInterval(function() {
        //     if (timer == 0) {
        //         location.href = 'https://www.jd.com/';
        //     } else {
        //         div.innerHTML = '您将在' + timer + '秒钟之后跳转到首页';
        //         timer--;
        //     }
        // })

        // 前面有一秒空白的解决方法
        k();   // 刷新页面时,有一秒的空白
        setInterval(function() {
            k();
        },1000)
        function k() {
            if (timer == 0) {
                location.href = 'https://www.jd.com/';
            } else {
                div.innerHTML = '您将在' + timer + '秒钟之后跳转到首页';
                timer--;
            }
        }
    </script>
</body>
</html>

The effect is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-OQcP2B3j-1668340396093)(Typora_image/460.png)]

5.5 Case: Obtain URL parameter data

The main practice data transfer in different pages.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-fNDq4xlI-1668340396094)(Typora_image/461.png)]

Create a new login.html file with the following code

<!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"  value="" />
        <input type="submit" name=""  value="登录" />	
    </form>
</body>
</html>

Create a new index.html file and execute the code as follows

<!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>
        console.log(location.search); // ?uname=andy
        // 1.先去掉?  substr('起始的位置',截取几个字符);
        var params = location.search.substr(1);   // uname=andy
        console.log(params);
        // 2.利用= 把字符串分割为数组 split('=')
        var arr = params.split('=');
        console.log(arr);  // ['uname','andy']
        var div = document.querySelector('div');
        // 3.把数据写入div中
        div.innerHTML = arr[1] + '欢迎您';
    </script>
</body>
</html>

The layout is as follows:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-NIHIT1pk-1668340396100)(Typora_image/462.png)]

The effect is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-APBNsyCw-1668340396102)(Typora_image/463.png)]

5.6 Methods of the location object

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-HYmAcQ0P-1668340396103)(Typora_image/464.png)]

Create a new .html file and execute the code as follows

<!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>
    <script>
        var btn = document.querySelector('button');
        btn.addEventListener('click',function() {
            // 记录浏览历史,所以可以实现后退功能
            // location.assign('https://www.jd.com/');
            // 不记录浏览历史,不可以实现后退功能
            // location.replace('https://www.taobao.com/')
            // 重新加载页面
            location.reload()

        })
    </script>
</body>
</html>

The effect is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-i1fS68y7-1668340396106)(Typora_image/465.png)]

6. The navigator object

The navigator object contains information about the browser. It has many properties. The most commonly used one is userAgent, which returns the value of the user-agent header sent by the client to the server.

The following front-end code can determine the user's terminal to open the page and realize the jump.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-kPGzgtnV-1668340396117)(Typora_image/466.png)]

7. History object

The window object provides us with a history object to interact with the browser history. This object contains URLs that the user has visited (in a browser window).

history object method effect
back() back function
forward() forward function
go(parameter) If the function parameter of forward and backward is 1, it will advance one page; if it is -1, it will go back one page.

Create a new index.html 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">点击   去列表页</a>
    <button>前进</button>
</body>
</html>

New list.html 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">点击   去列表页</a>
    <button>后退</button>
</body>
</html>

Its layout is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-IBh7xZlV-1668340396119)(Typora_image/467.png)]

The modified index.html code is as follows

<!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">点击   去列表页</a>
    <button>前进</button>

    <script>
        var btn = document.querySelector('button');
        btn.addEventListener('click',function() {
            // history.forward();
            history.go(1);
        })
    </script>
</body>
</html>

The modified list.html code is as follows

<!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">点击   去主页</a>
    <button>后退</button>
    <script>
        var btn = document.querySelector('button');
        btn.addEventListener('click',function() {
            // history.back();
            history.go(-1);
        })
    </script>
</body>
</html>

Example:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Ux6l4j0e-1668340396121)(Typora_image/468.png)]

Guess you like

Origin blog.csdn.net/m0_57021623/article/details/127836295