1.1. Common keyboard events

1.1.1 Keyboard Events

    <script>
        // Common keyboard events
        //1. Trigger when the keyUp button is pressed
        document.addEventListener('keyup'.function() {
            console.log('I bounced.');
        })

        //3. When the keyPress button is pressed, it triggers unrecognized function keys such as CTRL/SHIFT left and right arrows
        document.addEventListener('keypress'.function() {
                console.log('I pressed press');
        })
        //2. When the keyDown button is pressed, it triggers function keys such as CTRL/SHIFT left/right arrows
        document.addEventListener('keydown'.function() {
                console.log('I pressed down');
        })
        Keydown -- keypress -- keyup
    </script>
Copy the code

1.1.2 Keyboard event objects

Use the keyCode attribute to determine which key the user presses

    <script>
        // The keyCode property in the keyboard event object gets the ASCII value of the corresponding key
        document.addEventListener('keyup'.function(e) {
            console.log('up:' + e.keyCode);
            // We can use the ASCII value returned by keycode to determine which key the user pressed
            if (e.keyCode === 65) {
                alert('The A key you pressed');
            } else {
                alert('You didn't press the A key')}})document.addEventListener('keypress'.function(e) {
            // console.log(e);
            console.log('press:' + e.keyCode);
        })
    </script>
Copy the code

1.1.3 Case: Simulated jingdong key input content

When we press the S key, the cursor is positioned in the search box (the text box gets focus).

Note: The element object can be used to trigger the get focus event. Focus ()

    <input type="text">
    <script>
        // Get the input box
        var search = document.querySelector('input');
		// Register the keyUp event for document
        document.addEventListener('keyup'.function(e) {
            // Determine the value of keyCode
            if (e.keyCode === 83) {
                // Triggers a focus event for the input boxsearch.focus(); }})</script>
Copy the code

1.1.4 Case: Simulated jingdong express tracking number query

Requirement: When we enter content in the text box, the text box will automatically display large size content.

    <div class="search">
        <div class="con">123</div>
        <input type="text" placeholder="Please enter your tracking number" class="jd">
    </div>
    <script>
        // Get the element to operate on
        var con = document.querySelector('.con');
        var jd_input = document.querySelector('.jd');
		// Register the keyUp event for the input field
        jd_input.addEventListener('keyup'.function() {
				// Check whether the input box is empty
                if (this.value == ' ') {
                    // If empty, hide the zoom prompt box
                    con.style.display = 'none';
                } else {
                    // Not empty, display the enlargement prompt box, set the box content
                    con.style.display = 'block';
                    con.innerText = this.value; }})// Register the out-of-focus event for the input box, and hide the zoom prompt box
        jd_input.addEventListener('blur'.function() {
                con.style.display = 'none';
            })
        // Register the input field to get focus events
        jd_input.addEventListener('focus'.function() {
            // Check whether the input box is empty
            if (this.value ! = =' ') {
                // display the prompt box if it is not empty
                con.style.display = 'block'; }})</script>
Copy the code

1.2. BOM

1.2.1. What is 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.

1.2.2. BOM composition

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

1.2.3. The top-level object Window

1.2.4. Common events for window objects

Page (window) loading event (2 kinds)

1 kind

Window. onload is a window (page) load event,When the document content is fully loadedTriggers the event (including images, script files, CSS files, and so on) and invokes the handler function.

2 kinds of

The DOMContentLoaded event is triggered only when the DOM is loaded, excluding stylesheets, images, Flash, etc.

IE9 support only above!!

If there are many pictures on the page, it may take a long time from user access to onload trigger, and the interactive effect will not be realized, which will inevitably affect the user experience. In this case, DOMContentLoaded event is appropriate.

    <script>
        window.addEventListener('load'.function() {
            var btn = document.querySelector('button');
            btn.addEventListener('click'.function() {
                alert('Click me'); })})window.addEventListener('load'.function() {
            alert(22);
        })
        document.addEventListener('DOMContentLoaded'.function() {
            alert(33);
        })
    </script>
Copy the code

Resize window events

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

    <script>
        // Register page loading event
        window.addEventListener('load'.function() {
            var div = document.querySelector('div');
        	// Register the resize window event
            window.addEventListener('resize'.function() {
                // window.innerWidth Gets the window size
                console.log('Changed');
                if (window.innerWidth <= 800) {
                    div.style.display = 'none';
                } else {
                    div.style.display = 'block';
                }
            })
        })
    </script>
    <div></div>
Copy the code

1.2.5. Timer (two types)

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

  • setTimeout()

  • setInterval()

SetTimeout () Bomb timer

Start timer

Normal functions are called directly in code order. Simple understanding: callback, is back to call the meaning. Once the last thing is done, go back and call this function again. For example, the calling function in timer, the event handler function, is also a callback function. Element.onclick = function(){} or element.addeventListener (" click ", fn); The functions inside are also callback functions.Copy the code
    <script>
        The callback function is an anonymous function
         setTimeout(function() {
             console.log('Time is up');

         }, 2000);
        function callback() {
            console.log('Exploded');
        }
		// The callback function is a named function
        var timer1 = setTimeout(callback, 3000);
        var timer2 = setTimeout(callback, 5000);
    </script>
Copy the code
Example: Close the AD after 5 seconds

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

<button> Click stop timer </button><script>
        var btn = document.querySelector('button');
		// Start the timer
        var timer = setTimeout(function() {
            console.log('Exploded');
        }, 5000);
		// Register the click event for the button
        btn.addEventListener('click'.function() {
            // Stop the timer
            clearTimeout(timer);
        })
    </script>
Copy the code

SetInterval () Alarm timer

Start timer

    <script>
        // 1. setInterval 
        setInterval(function() {
            console.log('Continue output');
        }, 1000);
    </script>
Copy the code
Case study: Countdown

    <div>
        <span class="hour">1</span>
        <span class="minute">2</span>
        <span class="second">3</span>
    </div>
    <script>
        // 1. Get elements (minute box)
        var hour = document.querySelector('.hour'); // Hour black box
        var minute = document.querySelector('.minute'); // Minute black box
        var second = document.querySelector('.second'); // The number of seconds of the black box
        var inputTime = +new Date('the 2019-5-1 18:00:00'); // Returns the total number of milliseconds the user entered

        countDown(); // We call this function once to prevent blank pages from being refreshed the first time

        // 2. Start the timer
        setInterval(countDown, 1000);
		
        function countDown() {
            var nowTime = +new Date(a);// Returns the total number of milliseconds in the current time
            var times = (inputTime - nowTime) / 1000; // times is the total number of seconds left
            var h = parseInt(times / 60 / 60 % 24); / /
            h = h < 10 ? '0' + h : h;
            hour.innerHTML = h; // Give the remaining hours to the hour black box
            var m = parseInt(times / 60 % 60); / / points
            m = m < 10 ? '0' + m : m;
            minute.innerHTML = m;
            var s = parseInt(times % 60); // The current second
            s = s < 10 ? '0' + s : s;
            second.innerHTML = s;
        }
    </script>
Copy the code
Stop timer

Case: Send SMS countdown

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

Mobile number: <input type="number"> <button>send</button>
    <script>
        var btn = document.querySelector('button');
		// Global variable to define the number of seconds left
        var time = 3; 
		// Register the click event
        btn.addEventListener('click'.function() {
            // Disable button
            btn.disabled = true;
            // Start the timer
            var timer = setInterval(function() {
                // Determine the number of seconds left
                if (time == 0) {
                    // Clear timer and undo button
                    clearInterval(timer);
                    btn.disabled = false;
                    btn.innerHTML = 'send';
                } else {
                    btn.innerHTML = 'There's still something left' + time + '秒'; time--; }},1000);
        });
    </script>
Copy the code

1.2.6. This points to the problem

The direction of this is not determined during function definition. Only when the function is executed can it be determined who this refers to. In general, this refers to the object calling it.

For now, let’s look at a couple of this Pointers

  1. In a global scope or normal function, this refers to the global object Window.

  2. Whoever calls this points to in a method call

  3. Constructor this refers to an instance of the constructor

Click < button > < / button ><script>
        // This refers to the problem. In general, this eventually refers to the object that called it
        // 1. In the global scope or normal function, this refers to the global object Window.
        console.log(this);
        function fn() {
            console.log(this);
        }
        window.fn();
        window.setTimeout(function() {
            console.log(this);
        }, 1000);
        // 2. Who calls this in the method call refers to who
        var o = {
            sayHi: function() {
                console.log(this); // This refers to the object o
            }
        }
        o.sayHi();
        var btn = document.querySelector('button');
        btn.addEventListener('click'.function() {
                console.log(this); // This in the event handler refers to the BTN button object
            })
        // 3. Constructor this refers to an instance of the constructor
        function Fun() {
            console.log(this); // This points to the fun instance
        }
        var fun = new Fun();
    </script>
Copy the code

1.2.7. Location object

What is a Location object

URL

Location The property of the object

Example: The page is automatically redirected within 5 minutes

Click < button > < / 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.itcast.cn';
        })
        var timer = 5;
        setInterval(function() {
            if (timer == 0) {
                location.href = 'http://www.itcast.cn';
            } else {
                div.innerHTML = 'You will be in' + timer + 'Jump to home page in seconds'; timer--; }},1000);
    </script>
Copy the code

Example: Get URL parameters

    <div></div>
	<script>
        console.log(location.search); / /? uname=andy
        // 1. Substr (' starting position ', cut a few characters);
        var params = location.search.substr(1); // uname=andy
        console.log(params);
        // 2. Split string into array split('=');
        var arr = params.split('=');
        console.log(arr); // ["uname", "ANDY"]
        var div = document.querySelector('div');
        // 3. Write data to div
        div.innerHTML = arr[1] + 'Welcome';
    </script>
Copy the code

Common methods for location objects

Click < button > < / button ><script>
        var btn = document.querySelector('button');
        btn.addEventListener('click'.function() {
            // Record the browsing history, so you can implement the backward function
            // location.assign('http://www.itcast.cn');
            // The browser history is not recorded, so you cannot implement the backward function
            // location.replace('http://www.itcast.cn');
            location.reload(true);
        })
    </script>
Copy the code

1.2.8. 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|Fennec|wOSBrowser|BrowserNG|WebOS |Symbian|Windows Phone)/i))) {
    window.location.href = "";     / / cell phone
 } else {
    window.location.href = "";     / / computer
 }
Copy the code

1.2.9 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).

The history object is rarely used in real development, but is found in some OA office systems.

1.3. JS execution mechanism

What is the result of the following code execution?

 console.log(1);
 
 setTimeout(function () {
     console.log(3);
 }, 1000);
 
 console.log(2);
Copy the code

What is the result of the following code execution?

 console.log(1);
 
 setTimeout(function () {
     console.log(3);
 }, 0);
 
 console.log(2);
Copy the code

1.3.1 JS is single-threaded

Single threading means that all tasks need to be queued until the first one is finished before the next one can be executed. If the first task takes a long time, the second task has to wait forever. The problem with this is that if the JS execution takes too long, the rendering of the page will be incoherent, causing the page rendering load to feel blocked.Copy the code

1.3.2 Synchronous and Asynchronous Tasks

The problem with single threading is that later tasks wait for the previous task to complete, and if the previous task is time-consuming (such as reading network data), later tasks have to wait forever!!

In order to solve this problem, using the computing power of multi-core CPU, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, but the child threads are completely controlled by the main thread. As a result, synchronous and asynchronous tasks appear in JS.

synchronous

The execution of a task after the completion of the previous task, the order of the execution of the program and the order of the task is consistent, synchronous. For example, the simultaneous method of cooking: we boil the water to cook the rice, wait for the water to boil (10 minutes later), then cut the vegetables and fry the vegetables.

asynchronous

When you’re doing one thing, because it’s going to take a long time, you can do something else while you’re doing it. For example, the asynchronous way of cooking, we boil water at the same time, use the 10 minutes, to cut vegetables, stir-fry vegetables.

All tasks in JS can be categorized into two types, synchronous and asynchronous. A synchronization task refers to a task that is queued to be executed on the main thread. The next task can be executed only after the first task is completed. Asynchronous tasks refer to tasks that do not enter the main thread but enter the "task queue". When the tasks in the main thread are finished, the asynchronous tasks are removed from the "task queue" and put into the main thread for execution.Copy the code

1.3.3 JS Execution Mechanism (Event Loop)

1.3.4 Code thinking questions

 console.log(1);
 document.onclick = function() {
   console.log('click');
 }

 setTimeout(function() {
   console.log(3)},3000)
 console.log(2);
Copy the code