This is the 17th day of my participation in the August Text Challenge.More challenges in August

The concept of BOM

BOM(Browser Object Model) refers to the Browser Object Model, which provides a content-independent Object structure that can interact with the Browser window. The BOM is made up of several objects. The Window object representing the browser Window is the top object of the BOM, and all other objects are children of this object.

We can use BOM to programmatically handle all operations in the browser, such as refreshing the browser, backing up, advancing, and entering urls in the browser.

The window object

Window is the browser’s top-level object, and you can omit it when calling properties and methods under window.

Any global variable defined in the global scope is a property of the window.

Note:

The two special properties of window are window.name and window.top.

  • The special attribute name in window, if a new variable is defined, will only be assigned to the name attribute, and only string values will be assigned

  • In window, the value of the top property refers to the top-level object window, which is read-only and cannot be changed later.

So when defining global variables, don’t define name and top.

dialog

You don’t use dialog-box statements directly because you can’t execute subsequent code, so use tags to simulate. But it can be used in small cases.

  • alert()
  • prompt()
  • confirm()
    // A dialog box for the user to confirm or deselect
    // The confirm method returns a value, true if OK and false if cancel, depending on the button being clicked
    btn3.onclick = function () {
      var isSure = confirm("Excuse me, are you sure you want to delete this data?");
      console.log(isSure);
    };
Copy the code

The load event

The onload event

We can add an onload event to an element such as a window object or , which means that the event cannot be triggered until the element to which the event is bound is loaded.

The window object has been loaded, which means that all HTML structures have been loaded, and external imported resources (JS, CSS, IMG, video) have been loaded.

Note:

  1. Using the window.onload event, you can advance the JS code to the HTML structure.

You can write JavaScript in :

<script>
    // window.onload can only be used once per page
    window.onload = function () {
      // When the event is triggered, all page content has been loaded and there is no error in fetching elements
      var box = document.getElementById("box");
      var pics = document.getElementsByTagName("img");
      console.log(box.clientHeight);
    };
  </script>
Copy the code
  1. There can only be one window.onload event in a page.

decelerator

Set delay timer

A delay timer is a method of the Window object, similar to a time bomb. Is an asynchronous statement.

Grammar: window. SetTimeout (func, time); Window can be omitted

  • The first argument: the delayed function, which can be an anonymous function definition or a reference to a function name

Add ().

  • Second argument: delay time, in milliseconds, 1000 milliseconds is equal to 1 second.

Function: Delays the execution of a function after a specified time.

Note that in order to ensure that the delay can be cleared later, it needs to define an assignment to a variable

    var timeout = window.setTimeout(function () {
      console.log("boom");
    },2000);
Copy the code

Clear delay unit

A method of the window object

Grammar: window. ClearTimeout (timeout);

Parameter: The specified delayer variable name reference.

Function: Clear the specified delay device.

Note that the cleanup delay needs to be stored in a variable for later cleanup calls.

    // Clear the delay
    window.clearTimeout(timeout);
Copy the code

The timer

Set timer

A timer is a method of the Window object that is equivalent to a timer alarm clock that rings at fixed intervals

Grammar: window. SetInterval (func, interval);

  • The first argument: the function to be executed each time, which can be an anonymous function definition or a reference to the function name, without adding ().

  • Second argument: time interval, in milliseconds, 1000 milliseconds equals 1 second.

The first time a function is executed is after the first interval

Function: periodically executes a function at specified intervals.

Note that the timer must be stored in a variable when it is defined

Clear timer

A method of the window object

Grammar: window. ClearInterval (timer);

Parameter: Specifies the timer variable name reference.

Run the following command to clear a specified timer.

Note that the cleanup timer needs to be stored in a variable for later cleanup calls.

Clear timer problems

Question 1

The start and stop process of timer is written in different event functions, which is prone to user error click

1. Multiple clicks to start will cause acceleration

2, multiple clicks to start, can not stop

Click the Start button to move the box to the right. Click End to stop the box from moving

<body>
    <input type="button" value="Start" id="start">
    <input type="button" value="The end" id="end">
    <div class="box" id="box"></div>
    <script>
        // Get the element
        var start = document.getElementById("start");
        var end = document.getElementById("end");
        var box = document.getElementById("box");

        // The semaphore is changed each time it is reassigned
        // The initial semaphore value must be the same as the initial property value, left:0 so nowLeft=0
        var nowLeft = 0;

        / / timer
        var timer;

        start.onclick = function () {
            // Timer, make movement process
            timer = setInterval(function () {
                nowLeft += 10;
                box.style.left = nowLeft + "px";
            }, 100);
        };

        end.onclick = function(){
            clearInterval(timer);
        }
    </script>
</body>
Copy the code

In the above code, the start and end of the timer are written in different functions, and the two problems mentioned above occur. If the timer is not eliminated, it will always exist. Every time you click the Start button, the timer will point to a new timer from the original timer, and the step size of the timer will always accumulate. Even if you click the End button, you can only eliminate the current timer, but not the original existing timers.

The solution is to set the table first

Each time before starting a new timer, clear the previous timer

Add a line to start.onclick = function () to clear the timer:

        // Click the Start button to move the box to the right
        start.onclick = function () {
            clearInterval(timer);
            // Timer, make movement process
            timer = setInterval(function () {
                nowLeft += 10;
                box.style.left = nowLeft + "px";
            }, 100);
        };
Copy the code

Question 2

Requirement: Ask elements to stop at a specified location, such as 500px.

Problem: If the step size is not set properly, the stop position may not be exactly 500.

Solution Pull stopwatch

In the timer each time (each time the semaphore increase) to judge whether to come to the end, to stop the timer; If you reach or exceed the end point, forcibly pull to the point and stop the timer.

        // Click the Start button to move the box to the right
        start.onclick = function () {

            clearInterval(timer);
            // Timer, make movement process
            timer = setInterval(function () {
                nowLeft += 35;
                if(nowLeft >= 500) {// Force the variable to 500
                    nowLeft = 500;
                    
                    clearInterval(timer);
                }
                box.style.left = nowLeft + "px";
            }, 100);
        };
Copy the code

Question 3

Requirement: Let the element walk to the specified end position in a specified time, the time interval can be changed

For example, let the element go from 0 to 500px in 2 seconds.

Solution Step standard divisible

  • Total distance = step size * number of steps;

  • The interval is customized and the total duration is fixed

  • Find the total times = total time/time interval

Define a counter variable that increases the count by one for each execution of the timer function until the total number of executions is reached and the timer is stopped

<body>
    <input type="button" value="Start" id="start">
    <input type="button" value="The end" id="end">
    <div class="box" id="box"></div>

    <script>
        // Get the element
        var start = document.getElementById("start");
        var end = document.getElementById("end");
        var box = document.getElementById("box");

        var nowLeft = 0;
        var endLeft = 500;

        var time = 2000;
        var interval = 50;
        // count accumulator
        var count = 0

        / / total number
        var maxcount = time / interval;

        // Step size = (end position - start position)/(total time/interval)
        step = (endLeft - nowLeft) / maxcount;

    
        var timer;

        start.onclick = function(){
            timer = setInterval(function() {
                nowLeft += step;
                count ++;

                if(count >= maxcount){
                    // pull the stopwatch
                    nowLeft = endLeft;

                    clearInterval(timer);
                }


                box.style.left = nowLeft +"px";
            }, interval);
        }

    </script>
</body>
Copy the code

Simple movement

The principle of

Simple motion is a kind of visual transient effect. As long as the change time of elements is short enough, the effect caused to human eyes is a motion effect. The residual time of human eyes is between 0.1 and 0.4 seconds.

Production method through the timer, every other very short time (50-100 milliseconds or so), the execution of the function, the function of the movement of the property value changes.

Ways to increase the speed of movement

1, shorten the time interval, increase the number of movement per second. (Change the interval parameter in setInterval)

2, increase the step length, let each step increase. (Change the value added by the semaphore)

Location object

The location object is a property of the Window object, and can be used to omit the window object

Location Obtains or sets the URL of the browser address bar

A member of the location object

Use chrome’s console to view

Check MDN:developer.mozilla.org/zh-CN/

Members:

  • Methods: the assign ()/reload ()/replace ()

  • Properties: hash/host/hostname/search/href…

  1. The assign delegate

The assign() method, like the href attribute, sets the address to jump to

  1. The replace replace

Function: Replaces the current url in the address bar, but does not record history

  1. Reload reload

Similar to keyboard f5 function, similar to false effect, CTRL + F5 force refresh, get page from server, equivalent to true effect.

Arguments: true forces the page to be fetched from the server, false retrieves the page from the cache if the browser has cached the page

  1. The href attribute

Reassign, jump to a new page, and record history

URL

Uniform Resource Locator (URL)

Scheme ://host:port/path? query#fragment

  • For example: www.lagou.com:80/a/b/index.h…

Scheme: communication protocol, such as HTTP, FTP and MAIto

Host: the host name or IP address of the domain name System (DNS).

Port: indicates the port number. This parameter is optional. If omitted, use the default port number of the scheme.

Path: The path, a string separated by zero or more ‘/’ symbols, commonly used to indicate the address of a directory or file on the host.

Query: Optional, used to pass parameters to a dynamic web page. Multiple parameters can be separated by an ampersand, and the name and value of each parameter are separated by a =. For example: name = zs

Fragment: fragment of information, string, anchor.

The history object

The history object is a property of the Window object, and you can omit the window object when using it. But hardly any setup is required.

The History object interacts with the browser history, which is a chronological record and preservation of pages visited by the user.

Back () Rolls back historical records

Forward () to view the page after the previously recorded jump

Go () specifies the page to jump to

  • history.go(1)Go one page ahead
  • history.go(-1)Back up a page