What is the BOM

The Browser Object Model (BOM) is the Browser Object Model. It provides objects that interact with the Browser window independently of content. The core Object is window. A BOM is made up of a series of related objects, each of which provides a number of methods and attributes. BOM lacks standards. The standardization body for JavaScript syntax is ECMA, the standardization body for DOM is W3C, and BOM was originally part of the Netscape browser standard.

Summary of BOM

The structure of the BOM

The BOM is larger than the DOM, and it contains the DOM.

The structure of the BOM

The Window object is the top-level object of the browser and has a dual role. 1. It is an interface for JS to access the browser window. It is a global object. Variables and functions defined in the global scope become properties and methods of the Window object. You can omit the window when calling. The dialogs you learned earlier belong to window object methods, such as alert() and prompt(). Note: a special attribute under window, window.name

 <script>
        // window.document.querySelector()
        var num = 10;
        console.log(num);
        console.log(window.num);

        function fn() {
            console.log(11);

        }
        fn();
        window.fn();
        // alert(11);
        // window.alert(11)
        console.dir(window);
        // var name = 10;
        console.log(window.name);
    </script>
Copy the code

Common events for window objects

Window loading event mode 1

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

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

  1. With window.onload, you can write JS code at the top of a page element, because onload waits until the page is fully loaded before executing the handler function.
  2. Window. onload The traditional registration event can be written only once. If there are multiple registered events, the last window.onload takes effect.
  3. There are no restrictions if you use addEventListener

### Window loading event mode 2

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

The DOMContentLoaded event is triggered only when the DOM is loaded, excluding stylesheets, images, Flash, etc. If there are a lot of pictures on the page, it may take a long time from user access to onload trigger, and the interactive effect will not be able to achieve, which will inevitably affect the user experience. At this time, DOMContentLoaded event is more appropriate.

Resize window events

 window.onresize = function(){}

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

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

  1. This event is triggered whenever the window size changes by pixels.
  2. We often use this event for reactive layout. Window. innerWidth Width of the current screen

Example: Hide when browser window is less than or equal to 800

<body> <script> window.addEventListener('load', function() { var div = document.querySelector('div'); window.addEventListener('resize', function() { console.log(window.innerWidth); Console. log(' changed '); if (window.innerWidth <= 800) { div.style.display = 'none'; } else { div.style.display = 'block'; } }) }) </script> <div></div> </body>Copy the code

Two kinds of timer

The Window object gives us two very useful methods – timers.

 setTimeout() 
 setInterval()
Copy the code

1. SetTimeout () timer

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

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

  1. Window can be omitted.
  2. The call function can be written directly, either as a function name or as a string ‘function name ()’. The third is not recommended
  3. The number of milliseconds omitted defaults to 0 and must be milliseconds if written.
  4. Because timers can be many, we often assign an identifier to timers.
<script> // 1. setTimeout // syntax specification: window.settimeout (call function, delay time); // 1. The window can be omitted when called. // 2. The delay is in milliseconds but can be omitted. If omitted the default is 0 // 3. Function name (); // 4. // setTimeout(function() {// console.log(' time is up '); / /}, 2000); Function callback() {console.log(' exploded '); } var timer1 = setTimeout(callback, 3000); var timer2 = setTimeout(callback, 5000); // setTimeout('callback()', 3000); </script> </script>Copy the code

SetTimeout () is also called as callback. Normal functions are called in code order. This function, on the other hand, needs to wait until the time is up before calling this function, so it is called a callback function. Simple understanding: callback, is back to call the meaning. Once the last thing is done, go back and call this function again. Element.onclick = function(){} or element.addeventListener (” click “, fn); The functions inside are also callback functions.

Stop the setTimeout() timer

window.clearTimeout(timeoutID)
Copy the code

The clearTimeout() method cancels the timer previously established by calling setTimeout(). Note:

  1. Window can be omitted.
  2. The parameter inside is the timer identifier.

case

5 seconds after the automatic closing of the AD case analysis: 1, the core idea: 5 seconds after the AD is hidden 2, with the timer setTimeout code to achieve

<body>
    <img src="images/ad.jpg" alt="" class="ad">
    <script>
        var ad = document.querySelector('.ad');
        setTimeout(function() {
            ad.style.display = 'none';
        }, 5000);
    </script>
</body>
Copy the code

2. SetInterval () timer

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

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

1. Windows can be omitted. 2. This call can be written directly to the function, either as a function name or as a string 'function name ()'. The default is 0. If written, it must be milliseconds, indicating how many milliseconds this function is automatically called. 4. Because there can be many timers, we often assign an identifier to timers. 5. The first execution is performed after a number of milliseconds, and then every number of milliseconds.Copy the code

Stop the setInterval() timer

window.clearInterval(intervalID);
Copy the code

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

  1. Window can be omitted.
  2. The parameter inside is the timer identifier.

Case 1: Countdown

Case Study:

3. The number of hours, minutes and seconds that the three black boxes put into the calculation with innerHTML. 4. 5, it is best to use the method of encapsulation function, so that you can call this function first, to prevent the blank problem at the beginning of the page refreshCopy the code
 <style>
        div {
            margin: 200px;
        }
        
        span {
            display: inline-block;
            width: 40px;
            height: 40px;
            background-color: #333;
            font-size: 20px;
            color: #fff;
            text-align: center;
            line-height: 40px;
        }
    </style>
<body>
    <div>
        <span class="hour">1</span>
        <span class="minute">2</span>
        <span class="second">3</span>
    </div>
    <script>
        // 1. 获取元素 
        var hour = document.querySelector('.hour'); // 小时的黑色盒子
        var minute = document.querySelector('.minute'); // 分钟的黑色盒子
        var second = document.querySelector('.second'); // 秒数的黑色盒子
        var inputTime = +new Date('2019-5-1 18:00:00'); // 返回的是用户输入时间总的毫秒数
        countDown(); // 我们先调用一次这个函数,防止第一次刷新页面有空白 
        // 2. 开启定时器
        setInterval(countDown, 1000);

        function countDown() {
            var nowTime = +new Date(); // 返回的是当前时间总的毫秒数
            var times = (inputTime - nowTime) / 1000; // times是剩余时间总的秒数 
            var h = parseInt(times / 60 / 60 % 24); //时
            h = h < 10 ? '0' + h : h;
            hour.innerHTML = h; // 把剩余的小时给 小时黑色盒子
            var m = parseInt(times / 60 % 60); // 分
            m = m < 10 ? '0' + m : m;
            minute.innerHTML = m;
            var s = parseInt(times % 60); // 当前的秒
            s = s < 10 ? '0' + s : s;
            second.innerHTML = s;
        }
    </script>
</body>
Copy the code

Case 2: Sending SMS messages

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

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

Location object

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

What is the URL

Uniform Resource Locator (URL) is the address of a standard Resource on the Internet. Every file on the Internet has a unique URL that contains information indicating where the file is and what the browser should do with it. The general syntax format of a URL is:

 protocol://host[:port]/path/[?query]#fragment

 http://www.itcast.cn/index.html?name=andy&age=18#link
Copy the code

Location The property of the object

Key things to remember: href and search examples:

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

Location object method

<body> <button> click </button> <script> var BTN = document.querySelector('button'); Btn.addeventlistener ('click', function() {// Record the browser history, so can implement the back function location.assign('http://www.itcast.cn'); Location. replace('http://www.itcast.cn'); // Refresh the page location.reload(); // Some resources are fetched from the cache location.reload(true); }) </script> </body>Copy the code

The navigator object

The Navigator object contains information about the browser and has a number of properties, the most common being the userAgent, which returns the value of the User-Agent header of the server sent by the client. The following front-end code can determine which terminal users open the page, to achieve the jump

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

The history object

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

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