01Web API

learning target:

Able to get the elements by ID
can be obtained elements by tag name
can be acquired elements by class
able to get the elements through the selector
can obtain body and html elements
can give elements registered event
can modify the content of the element
able to distinguish the difference between innerText and innerHTML is
capable of modify the properties of common elements such as div
can modify the properties of form elements
can modify the style attributes of the element

1.1. Web API introduction

The concept of 1.1.1 API

API (Application Programming Interface, Application Programming Interface) is a function of a number of pre-defined in order to provide application developers with a software or hardware-based capability to access a set of routines, but without accessing the source code without having to understand its internal the working mechanism of the details, you can simply use a direct call.

Examples explain what API.

E.g,

C language has a function fopen () can open a file on the hard drive, this function tool for us, is a C language provides open files.

There is a function in javascript alert () can bomb the page a prompt box, this function is a bomb js tool box provided.

These tools (functions) provided by the programming language, the internal implementation has a good package, we just have to learn and flexible to use these tools.

1.1.2 Web API concept of

Web API is a set of browser functionality and operation of page elements provided by the browser API (BOM and DOM).

At present, we aimed to explain commonly used browser API, the main job of interactivity for the browser. For example, we want the browser pop up a warning box, directly alert ( 'pop-up')

MDN detailed API: https://developer.mozilla.org/zh-CN/docs/Web/API

Because many Web API, so we will at this stage is called Web APIs.

Web API here refers specifically to a series of API (a lot of function or object method) provided by the browser, that is operating a range of tools web page. For example: html tags operating method for operating a page address.

1.1.3 API and Web API summary

  1. API is an interface to provide for our programmers to help us achieve certain functions, we will use it, do not tangle how to achieve internal

  2. Web API is mainly aimed at providing an interface to the browser, the main target in the browser to do interactivity.

  3. Web API generally have input and output (pass parameters and return value of the function), Web API are many methods (functions)

  4. Learning Web API built-in objects can be combined with the previous method of learning to learn ideas

1.2. DOM Introduction

1.2.1 What is the DOM

Document Object Model (Document Object Model, referred to as DOM), is a W3C -recommended treatment extensible markup language (html or xhtml) of standard programming interfaces .

The W3C has defined a series of DOM interface, you can change the content, structure and style through these pages DOM interface.

DOM is a standardized set of processing html and xml documents W3C organizations to develop, all browsers have followed this standard.

1.2.2. DOM tree

DOM tree is also called the document tree model, the document mapped into a tree structure, through its processing node object, the result of processing can be added to the current page.

  • Documentation: a page is a document, DOM representation used in document
  • Node: All content in web pages, all the nodes in the document tree (tags, attributes, text, comments, etc.), using the node represents
  • Tags node: all labels page, commonly referred to as an element node, but also referred to as "elements", using the element represents

1.3. Getting an element

Why get a page element?

For example: We want to operate on a certain part of the page (show / hide, animation), you need to get to the part corresponding to the elements, and then manipulate it.

1.3.1. According to acquire ID

语法:document.getElementById(id)
作用:根据ID获取元素对象
参数:id值,区分大小写的字符串
返回值:元素对象 或 null

Case Code

<body>
    <div id="time">2019-9-9</div>
    <script>
        // 因为我们文档页面从上往下加载,所以先得有标签 所以我们script写到标签的下面
        var timer = document.getElementById('time');
        console.log(timer);//<div id="time">2019-9-9</div>
        console.log(typeof timer);//object
        // console.dir 打印我们返回的元素对象 更好的查看里面的属性和方法
        console.dir(timer);//div#time
    </script>
</body>

1.3.2. Getting an element according to the label name

语法:document.getElementsByTagName('标签名') 或者 element.getElementsByTagName('标签名') 
作用:根据标签名获取元素对象
参数:标签名
返回值:元素对象集合(伪数组,数组元素是元素对象)

Case Code

<body>
    <ul>
        <li>知否知否,应是等你好久11</li>
        <li>知否知否,应是等你好久22</li>
        <li>知否知否,应是等你好久33</li>
        <li>知否知否,应是等你好久44</li>
        <li>知否知否,应是等你好久55</li>
    </ul>
    <ul id="nav">
        <li>生僻字</li>
        <li>生僻字</li>
        <li>生僻字</li>
        <li>生僻字</li>
        <li>生僻字</li>
    </ul>
    <script>
        // 1.返回的是 获取过来元素对象的集合 以伪数组的形式存储的
        var lis = document.getElementsByTagName('li');
        console.log(lis);
        console.log(lis[0]);
        // 2. 我们想要依次打印里面的元素对象我们可以采取遍历的方式
        for (var i = 0; i < lis.length; i++) {
            console.log(lis[i]);
        }
        // 3. element.getElementsByTagName()  可以得到这个元素里面的某些标签
        var nav = document.getElementById('nav'); // 这个获得nav 元素
        var navLis = nav.getElementsByTagName('li');
        console.log(navLis);
    </script>
</body>

注意:getElementsByTagName()获取到是动态集合,即:当页面增加了标签,这个集合中也就增加了元素。

1.3.3. H5新增获取元素方式

案例代码

<body>
    <div class="box">盒子1</div>
    <div class="box">盒子2</div>
    <div id="nav">
        <ul>
            <li>首页</li>
            <li>产品</li>
        </ul>
    </div>
    <script>
        // 1. getElementsByClassName 根据类名获得某些元素集合
        var boxs = document.getElementsByClassName('box');
        console.log(boxs);
        // 2. querySelector 返回指定选择器的第一个元素对象  切记 里面的选择器需要加符号 .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()返回指定选择器的所有元素对象集合
        var allBox = document.querySelectorAll('.box');
        console.log(allBox);
        var lis = document.querySelectorAll('li');
        console.log(lis);
    </script>
</body>

1.3.4 获取特殊元素(body,html)

1.4. 事件基础

1.4.1. 事件概述

JavaScript 使我们有能力创建动态页面,而事件是可以被 JavaScript 侦测到的行为。

简单理解: 触发--- 响应机制

​ 网页中的每个元素都可以产生某些可以触发 JavaScript 的事件,例如,我们可以在用户点击某按钮时产生一个 事件,然后去执行某些操作。

1.4.2. 事件三要素

  • 事件源(谁):触发事件的元素
  • 事件类型(什么事件): 例如 click 点击事件
  • 事件处理程序(做啥):事件触发后要执行的代码(函数形式),事件处理函数

案例代码

<body>
    <button id="btn">唐伯虎</button>
    <script>
        // 点击一个按钮,弹出对话框
        // 1. 事件是有三部分组成  事件源  事件类型  事件处理程序   我们也称为事件三要素
        //(1) 事件源 事件被触发的对象   谁  按钮
        var btn = document.getElementById('btn');
        //(2) 事件类型  如何触发 什么事件 比如鼠标点击(onclick) 还是鼠标经过 还是键盘按下
        //(3) 事件处理程序  通过一个函数赋值的方式 完成
        btn.onclick = function() {
            alert('点秋香');
        }
    </script>
</body>

1.4.3. 执行事件的步骤

1550734387056

案例代码

<body>
    <div>123</div>
    <script>
        // 执行事件步骤
        // 点击div 控制台输出 我被选中了
        // 1. 获取事件源
        var div = document.querySelector('div');
        // 2.绑定事件 注册事件
        // div.onclick 
        // 3.添加事件处理程序 
        div.onclick = function() {
            console.log('我被选中了');
        }
    </script>
</body>

1.4.4. 常见的鼠标事件

1.4.5. 分析事件三要素

  • 下拉菜单三要素

  • 关闭广告三要素

1.5. 操作元素

​ JavaScript的 DOM 操作可以改变网页内容、结构和样式,我们可以利用 DOM 操作元素来改变元素里面的内容、属性等。(注意:这些操作都是通过元素对象的属性实现的)

1.5.1. 改变元素内容(获取或设置)

innerText改变元素内容

<body>
    <button>显示当前系统时间</button>
    <div>某个时间</div>
    <p>1123</p>
    <script>
        // 当我们点击了按钮,  div里面的文字会发生变化
        // 1. 获取元素 
        var btn = document.querySelector('button');
        var div = document.querySelector('div');
        // 2.注册事件
        btn.onclick = function() {
            // div.innerText = '2019-6-6';
            div.innerHTML = getDate();
        }
        function getDate() {
            var date = new Date();
            // 我们写一个 2019年 5月 1日 星期三
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var dates = date.getDate();
            var arr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
            var day = date.getDay();
            return '今天是:' + year + '年' + month + '月' + dates + '日 ' + arr[day];
        }
    </script>
</body>

innerText和innerHTML的区别

  • 获取内容时的区别:

​ innerText会去除空格和换行,而innerHTML会保留空格和换行

  • 设置内容时的区别:

​ innerText不会识别html,而innerHTML会识别

案例代码

<body>
    <div></div>
    <p>
        我是文字
        <span>123</span>
    </p>
    <script>
        // innerText 和 innerHTML的区别 
        // 1. innerText 不识别html标签 非标准  去除空格和换行
        var div = document.querySelector('div');
        // div.innerText = '<strong>今天是:</strong> 2019';
        // 2. innerHTML 识别html标签 W3C标准 保留空格和换行的
        div.innerHTML = '<strong>今天是:</strong> 2019';
        // 这两个属性是可读写的  可以获取元素里面的内容
        var p = document.querySelector('p');
        console.log(p.innerText);
        console.log(p.innerHTML);
    </script>
</body>

1.5.2. 常用元素的属性操作

获取属性的值

元素对象.属性名

设置属性的值

元素对象.属性名 = 值

案例代码

<body>
    <button id="ldh">刘德华</button>
    <button id="zxy">张学友</button> <br>
    <img src="images/ldh.jpg" alt="" title="刘德华">
    <script>
        // 修改元素属性  src
        // 1. 获取元素
        var ldh = document.getElementById('ldh');
        var zxy = document.getElementById('zxy');
        var img = document.querySelector('img');
        // 2. 注册事件  处理程序
        zxy.onclick = function() {
            img.src = 'images/zxy.jpg';
            img.title = '张学友思密达';
        }
        ldh.onclick = function() {
            img.src = 'images/ldh.jpg';
            img.title = '刘德华';
        }
    </script>
</body>

1.5.3. 案例:分时问候

<body>
    <img src="images/s.gif" alt="">
    <div>上午好</div>
    <script>
        // 根据系统不同时间来判断,所以需要用到日期内置对象
        // 利用多分支语句来设置不同的图片
        // 需要一个图片,并且根据时间修改图片,就需要用到操作元素src属性
        // 需要一个div元素,显示不同问候语,修改元素内容即可
        // 1.获取元素
        var img = document.querySelector('img');
        var div = document.querySelector('div');
        // 2. 得到当前的小时数
        var date = new Date();
        var h = date.getHours();
        // 3. 判断小时数改变图片和文字信息
        if (h < 12) {
            img.src = 'images/s.gif';
            div.innerHTML = '亲,上午好,好好写代码';
        } else if (h < 18) {
            img.src = 'images/x.gif';
            div.innerHTML = '亲,下午好,好好写代码';
        } else {
            img.src = 'images/w.gif';
            div.innerHTML = '亲,晚上好,好好写代码';

        }
    </script>
</body>

1.5.4. 表单元素的属性操作

获取属性的值

元素对象.属性名

设置属性的值

元素对象.属性名 = 值

表单元素中有一些属性如:disabled、checked、selected,元素对象的这些属性的值是布尔型。

案例代码

<body>
    <button>按钮</button>
    <input type="text" value="输入内容">
    <script>
        // 1. 获取元素
        var btn = document.querySelector('button');
        var input = document.querySelector('input');
        // 2. 注册事件 处理程序
        btn.onclick = function() {
            // 表单里面的值 文字内容是通过 value 来修改的
            input.value = '被点击了';
            // 如果想要某个表单被禁用 不能再点击 disabled  我们想要这个按钮 button禁用
            // btn.disabled = true;
            this.disabled = true;
            // this 指向的是事件函数的调用者 btn
        }
    </script>
</body>

1.5.5. 案例:仿京东显示密码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box {
            position: relative;
            width: 400px;
            border-bottom: 1px solid #ccc;
            margin: 100px auto;
        }
        
        .box input {
            width: 370px;
            height: 30px;
            border: 0;
            outline: none;
        }
        
        .box img {
            position: absolute;
            top: 2px;
            right: 2px;
            width: 24px;
        }
    </style>
</head>

<body>
    <div class="box">
        <label for="">
            <img src="images/close.png" alt="" id="eye">
        </label>
        <input type="password" name="" id="pwd">
    </div>
    <script>
        // 1. 获取元素
        var eye = document.getElementById('eye');
        var pwd = document.getElementById('pwd');
        // 2. 注册事件 处理程序
        var flag = 0;
        eye.onclick = function() {
            // 点击一次之后, flag 一定要变化
            if (flag == 0) {
                pwd.type = 'text';
                eye.src = 'images/open.png';
                flag = 1; // 赋值操作
            } else {
                pwd.type = 'password';
                eye.src = 'images/close.png';
                flag = 0;
            }

        }
    </script>
</body>

</html>

1.5.6. 样式属性操作

我们可以通过 JS 修改元素的大小、颜色、位置等样式。

常用方式

方式1:通过操作style属性

元素对象的style属性也是一个对象!

元素对象.style.样式属性 = 值;

案例代码

<body>
    <div></div>
    <script>
        // 1. 获取元素
        var div = document.querySelector('div');
        // 2. 注册事件 处理程序
        div.onclick = function() {
            // div.style里面的属性 采取驼峰命名法 
            this.style.backgroundColor = 'purple';
            this.style.width = '250px';
        }
    </script>
</body>

案例:淘宝点击关闭二维码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box {
            position: relative;
            width: 74px;
            height: 88px;
            border: 1px solid #ccc;
            margin: 100px auto;
            font-size: 12px;
            text-align: center;
            color: #f40;
            /* display: block; */
        }
        
        .box img {
            width: 60px;
            margin-top: 5px;
        }
        
        .close-btn {
            position: absolute;
            top: -1px;
            left: -16px;
            width: 14px;
            height: 14px;
            border: 1px solid #ccc;
            line-height: 14px;
            font-family: Arial, Helvetica, sans-serif;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div class="box">
        淘宝二维码
        <img src="images/tao.png" alt="">
        <i class="close-btn">×</i>
    </div>
    <script>
        // 1. 获取元素 
        var btn = document.querySelector('.close-btn');
        var box = document.querySelector('.box');
        // 2.注册事件 程序处理
        btn.onclick = function() {
            box.style.display = 'none';
        }
    </script>
</body>

</html>

案例:显示隐藏文本框内容

方式2:通过操作className属性

元素对象.className = 值;

因为class是关键字,所有使用className。

1550737214510

案例代码

<body>
    <div class="first">文本</div>
    <script>
        // 1. 使用 element.style 获得修改元素样式  如果样式比较少 或者 功能简单的情况下使用
        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. 我们可以通过 修改元素的className更改元素的样式 适合于样式较多或者功能复杂的情况
            // 3. 如果想要保留原先的类名,我们可以这么做 多类名选择器
            // this.className = 'change';
            this.className = 'first change';
        }
    </script>
</body>

Guess you like

Origin www.cnblogs.com/fly-book/p/12106726.html