Day 1 - Web APIs

Learning objectives:

Elements can be obtained by ID, elements can be obtained by tag name, elements can be obtained by class, elements can be obtained by selector, elements can be obtained by body and html elements can register events for elements can modify the contents of elements can distinguish between innerText and innerHTML can modify the properties of common elements such as div can modify the properties of form elements Enough to modify the style properties of an element

1.1. Introduction to Web APIs

1.1.1 API concepts

API s (Application Programming Interface s) are predefined functions designed to provide applications and developers with the ability to access a set of routines based on a piece of software or hardware without access to the source code, without understanding the details of their internal mechanisms of work, and simply by calling them directly.

Examples explain what an API is.

For example,

There is a function fopen() in C to open files on the hard disk. For us, this function is a tool to open files provided by C.

There is a function alert() in javascript that pops up a prompt box on the page, which is a pop-up box tool provided by js.

These tools (functions) are provided by the programming language, the internal implementation is encapsulated, and we just need to learn to use them flexibly.

1.1.2 Web API concepts

The Web API is a set of APIs (BOM and DOM) that browsers provide to manipulate browser functions and page elements.

At this stage, we mainly focus on the browser to explain the commonly used API, mainly for the browser to do interactive effects. For example, if we want our browser to pop up a warning box, use alert directly ('pop-up')

MDN Detailed API: Web API Interface Reference | MDN

Because there are many Web APIs, we call this stage Web APIs.

The Web API here refers specifically to a series of APIs (many functions or object methods) provided by the browser, a series of tools for manipulating web pages. Examples are: how to manipulate html tags, how to manipulate page addresses.

1.1.3 API and Web API Summary

  1. The API is an interface for our programmers to help us implement a function that we can use without having to worry about how we implement it internally

  2. The Web API is mainly for the interface provided by the browser, mainly for the interactive effect of the browser.

  3. Web API s generally have inputs and outputs (parameters and return values of functions), many of which are methods (functions)

  4. Learning Web API s can be combined with previous ideas for learning the built-in object approach

1.2. Introduction to DOM

1.2.1 What is DOM

The Document Object Model (DOM) is W3C Organizational Recommended Processing Extensible Markup Language Standards for (html or xhtml) Programming Interface.

W3C has defined a series of DOM interfaces that can change the content, structure and style of Web pages.

DOM is a set of specifications developed by the W3C organization for handling html and xml documents, which all browsers follow.

1.2.2. DOM Tree

 

The DOM tree, also known as the Document Tree Model, maps a document into a tree structure, which is processed by node objects, and the results of the processing can be added to the current page.

  • Document: A page is a document, represented by a document in the DOM

  • Node: Everything in a Web page is a node (label, attribute, text, comment, etc.) in the document tree, represented by a node

  • Tag node: All tags in a Web page, commonly referred to as element nodes, or simply "elements", are represented by an element

1.3. Get Elements

Why get page elements?

For example, if we want to manipulate a part of a page (show/hide, animation), we need to get the corresponding elements of that part before we can manipulate it.

1.3.1. Obtained by ID

Syntax: document.getElementById(id)
Role: Get element objects based on ID
 Parameter: id value, case-sensitive string
 Return value: Element object or null

Case Code

<body>
    <div id="time">2019-9-9</div>
    <script>
        // Because our document pages are loaded from top to bottom, we have to have a label first, so we script to the bottom of the label
        var timer = document.getElementById('time');
        console.log(timer);
        console.log(typeof timer);
        // console.dir prints the element objects we return to better see the properties and methods inside
        console.dir(timer);
    </script>
</body>

1.3.2. Get elements by tag name

Syntax: document.getElementsByTagName('tag name') or element.getElementsByTagName('tag name') 
Role: Get the element object based on the label name
 Parameter: Label name
 Return value: collection of element objects (pseudo array, array elements are element objects)

Case Code

<body>
    <ul>
        <li>Whether or not, should wait for you for a long time 11</li>
        <li>Whether or not, should wait for you for a long time 22</li>
        <li>Whether or not, should wait for you for a long time 33</li>
        <li>Whether or not, should wait for you for a long time 44</li>
        <li>Whether or not, should wait for you for a long time 55</li>
    </ul>
    <ul id="nav">
        <li>Uncommon Words</li>
        <li>Uncommon Words</li>
        <li>Uncommon Words</li>
        <li>Uncommon Words</li>
        <li>Uncommon Words</li>
    </ul>
    <script>
        // 1. Returns a collection of element objects retrieved and stored as a pseudo-array
        var lis = document.getElementsByTagName('li');
        console.log(lis);
        console.log(lis[0]);
        // 2. If we want to print the element objects in turn, we can traverse through them
        for (var i = 0; i < lis.length; i++) {
            console.log(lis[i]);
        }
        // 3. element.getElementsByTagName() gets some tags inside this element
        var nav = document.getElementById('nav'); // This takes the nav element
        var navLis = nav.getElementsByTagName('li');
        console.log(navLis);
    </script>
</body>

 

Note: getElementsByTagName() gets a dynamic collection, that is, when a page adds a tag, an element is added to the collection.

1.3.3. H5 New ways to get elements

 

 

Case Code

<body>
    <div class="box">Box 1</div>
    <div class="box">Box 2</div>
    <div id="nav">
        <ul>
            <li>home page</li>
            <li>product</li>
        </ul>
    </div>
    <script>
        // 1. getElementsByClassName obtains a collection of elements based on the class name
        var boxs = document.getElementsByClassName('box');
        console.log(boxs);
        // 2. querySelector returns the first element object of the specified selector Remember that the selector inside needs to be symbolized.box #nav
        var firstBox = document.querySelector('.box');
        console.log(firstBox);
        var nav = document.querySelector('#nav');
        console.log(nav);
        var li = document.querySelector('li');
        console.log(li);
        // 3. querySelectorAll() returns a collection of all element objects for the specified selector
        var allBox = document.querySelectorAll('.box');
        console.log(allBox);
        var lis = document.querySelectorAll('li');
        console.log(lis);
    </script>
</body>

1.3.4 Get special elements (body, html)

 

1.4. Event Base

1.4.1. Overview of events

JavaScript gives us the ability to create dynamic pages, and events are behaviors that JavaScript can detect.

Simple understanding: trigger - response mechanism.

Every element in a Web page can produce certain events that trigger JavaScript. For example, we can generate an event when a user clicks a button and then perform certain actions.

1.4.2. Three Elements of Events

  • Event Source (who): The element that triggers the event

  • Event type (what event): such as click click event

  • Event handler (what to do): code to execute after an event is triggered (in the form of a function), event handler function

Case Code

<body>
    <button id="btn">Tang Bo Hu</button>
    <script>
        // Click a button to bring up a dialog box
        // 1. An event is a three-part event source event type event handler    We also call these three elements of events
        //(1) The object triggered by the event source event    Who button
        var btn = document.getElementById('btn');
        //(2) How event types trigger something, such as an onclick, a mouse-over, or a keyboard-down
        //(3) Event handlers are accomplished by assigning a function
        btn.onclick = function() {
            alert('Autumn scent');
        }
    </script>
</body>

1.4.3. Steps to execute the event

 

Case Code

<body>
    <div>123</div>
    <script>
        // Execute Event Steps
        // Click on the div console to output that I'm selected
        // 1. Get the event source
        var div = document.querySelector('div');
        // 2. Binding Event Registration Events
        // div.onclick 
        // 3. Add event handlers 
        div.onclick = function() {
            console.log('I was selected');
        }
    </script>
</body>

1.4.4. Common mouse events

1.4.5. Analyzing the three elements of an event

  • Drop-down menu three elements

  • Close three elements of advertising

1.5. Action Elements

JavaScript DOM operations can change the content, structure and style of Web pages. We can use DOM operations to change the content, attributes, etc. inside elements. (Note: All these operations are done through the properties of the element object)

1.5.1. Change element content (get or set)

innerText changes element content

<body>
    <button>Display the current system time</button>
    <div>At a time</div>
    <p>1123</p>
    <script>
        // When we click the button, the text in the div changes
        // 1. Get Elements 
        var btn = document.querySelector('button');
        var div = document.querySelector('div');
        // 2. Registration Events
        btn.onclick = function() {
            // div.innerText = '2019-6-6';
            div.innerHTML = getDate();
        }
        function getDate() {
            var date = new Date();
            // Let's write a Wednesday, May 1, 2019
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var dates = date.getDate();
            var arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
            var day = date.getDay();
            return 'Today is:' + year + 'year' + month + 'month' + dates + 'day ' + arr[day];
        }
    </script>
</body>

The difference between innerText and innerHTML

  • Differences when getting content:

innerText removes whitespace and line breaks, while innerHTML retains whitespace and line breaks

  • Differences when setting content:

innerText does not recognize html, but innerHTML does

Case Code

<body>
    <div></div>
    <p>
        I am text
        <span>123</span>
    </p>
    <script>
        // The difference between innerText and innerHTML 
        // 1. innerText does not recognize html tags non-standard whitespace removal and line breaks
        var div = document.querySelector('div');
        // Div.innerText ='<strong>Today is: </strong> 2019';
        // 2. innerHTML recognizes html tag W3C standard reserved spaces and newlines
        div.innerHTML = '<strong>Today is:</strong> 2019';
        // These two attributes are readable, writable, and retrievable within the element
        var p = document.querySelector('p');
        console.log(p.innerText);
        console.log(p.innerHTML);
    </script>
</body>

1.5.2. Attribute operations for common elements

 

 

Get the value of the property

Element objects. Attribute names

Set the value of the property

Element object. Attribute name = value

Case Code

<body>
    <button id="ldh">Lau Andy</button>
    <button id="zxy">Jacky Cheung</button> <br>
    <img src="images/ldh.jpg" alt="" title="Lau Andy">
    <script>
        // Modify element attribute src
        // 1. Get Elements
        var ldh = document.getElementById('ldh');
        var zxy = document.getElementById('zxy');
        var img = document.querySelector('img');
        // 2. Register event handlers
        zxy.onclick = function() {
            img.src = 'images/zxy.jpg';
            img.title = 'Zhang Xueyou Smith';
        }
        ldh.onclick = function() {
            img.src = 'images/ldh.jpg';
            img.title = 'Lau Andy';
        }
    </script>
</body>

1.5.3. Case: Time Sharing Greetings

 

 

1.5.4. Attribute operations on form elements

 

Get the value of the property

Element objects. Attribute names

Set the value of the property

Element object. Attribute name = value

There are some attributes in the form element such as disabled, checked, selected. The values of these attributes of the element object are Boolean.

Case Code

<body>
    <button>Button</button>
    <input type="text" value="Input Content">
    <script>
        // 1. Get Elements
        var btn = document.querySelector('button');
        var input = document.querySelector('input');
        // 2. Register event handlers
        btn.onclick = function() {
            // Value text content in the form is modified by value
            input.value = 'Clicked on';
            // If you want a form to be disabled you can no longer click disabled We want this button to be disabled
            // btn.disabled = true;
            this.disabled = true;
            // this points to the caller btn of the event function
        }
    </script>
</body>

1.5.5. Case: imitate Jingdong display password

 

 

1.5.6. Style attribute operations

We can modify the size, color, position and other styles of elements through JS.

Common ways

 

Mode 1: By manipulating the style attribute

The style attribute of an element object is also an object!

Element object.style.Style attribute=value;

 

Case Code

<body>
    <div></div>
    <script>
        // 1. Get Elements
        var div = document.querySelector('div');
        // 2. Register event handlers
        div.onclick = function() {
            // The attributes inside div.style are named by the hump 
            this.style.backgroundColor = 'purple';
            this.style.width = '250px';
        }
    </script>
</body>

Case: Taobao Click to Close QR Code

 

 

Case: Circle Wizard Background

 

 

Case: Show hidden text box content

 

 

Mode 2: By manipulating the className attribute

Element object.className =value;

Because class is the keyword, all use className.

 

Case Code

<body>
    <div class="first">text</div>
    <script>
        // 1. Use element.style to get modifications to element styles if they are less styled or simple to use
        var test = document.querySelector('div');
        test.onclick = function() {
            // this.style.backgroundColor = 'purple';
            // this.style.color = '#fff';
            // this.style.fontSize = '25px';
            // this.style.marginTop = '100px';

            // 2. We can change the style of an element by modifying its className to suit more styled or more complex situations
            // 3. If you want to keep the original class name, we can do this with a multi-class name selector
            // this.className = 'change';
            this.className = 'first change';
        }
    </script>
</body>

Case: Password box format prompt error message

 

 

 

1.6. Summary Today

 

Tags: Javascript Front-end

Posted on Sat, 27 Nov 2021 12:21:06 -0500 by DeadDude