前端 --- JavaScript WebAPI

x33g5p2x  于2022-04-19 转载在 Java  
字(12.2k)|赞(0)|评价(0)|浏览(300)

1. WebAPI 背景知识

1.1 什么是 WebAPI

JS 分成三个大的部分:

  • ECMAScript: 基础语法部分
  • DOM API: 操作页面结构
  • BOM API: 操作浏览器

WebAPI 就包含了 DOM + BOM.

1.2 DOM 基本概念

什么是 DOM

DOM 全称为 Document Object Model.

W3C 标准给我们提供了一系列的函数, 让我们可以操作:

  1. 网页内容
  2. 网页结构
  3. 网页样式

DOM 树

一个页面的结构是一个树形结构, 称为 DOM 树.

重要概念:

  • 文档: 一个页面就是一个 文档, 使用 document 表示.
  • 元素: 页面中所有的标签都称为 元素. 使用 element表示.
  • 节点: 网页中所有的内容都可以称为 节点(标签节点, 注释节点, 文本节点, 属性节点等). 使用 node表示.

2. 获取元素

2.1 querySelector

使用 querySelector能够完全复用前面学过的 CSS 选择器知识, 达到更快捷更精准的方式获取到元素对象

语法格式:

let element = document.querySelector(selectirs);
  • selectors 填一个或者多个选择器

使用示例:

<div class="one"> abc </div>
    <div id="two"> def </div>
    <div><input type="text"></div>
    <script>
        let one = document.querySelector('.one');
        console.log(one);
        let two = document.querySelector('#two');
        console.log(two);
        let three = document.querySelector('input');
        console.log(three);
    </script>

运行截图

2.2 querySelectorAll

如果您需要与指定选择器匹配的所有元素的列表,则应该使用 querySelectorAll()

使用示例:

<div class="one">123</div>
    <div id="two">456</div>
    <script>
        let divs = document.querySelectorAll('div');
        console.log(divs);
    </script>

运行截图

3. 操作元素

3.1 获取/修改元素内容

1. innerText

Element.innerText属性表示一个节点及其后代的“渲染”文本内容

**注:**不识别 html 标签. 是非标准的(IE发起的). 读取结果不保留html源码中的 换行和空格.

使用示例:

<div class="one">hello world</div>
    <div class="two">hello world</div>
    <script>
        let div = document.querySelector('.two');
        console.log(div);
        div.innerText = '<span>world hello</span>';
    </script>

运行截图:

通过 innerText无法获取div 内部的 html 结构, 只能得到文本内容.

2. innerHTML

Element.innerHTML 属性设置或获取HTML语法表示的元素的后代
注意:

  • 识别 html 标签. W3C 标准的. 读取结果保留html源码中的 换行 和 空格

代码示例:

<div class="one">hello world</div>
    <div class="two">hello world</div>
    <script>
        let div = document.querySelector('.two');
        console.log(div);
        div.innerHTML = '<span>world hello</span>';
    </script>

运行截图:

innerHTML 不光能获取到页面的 html结构, 同时也能修改结构. 并且获取到的内容保留的空格和换行

3.2 获取/修改元素属性

注: 通过 element.属性来获取属性
代码示例:

<img src="male.png" title="男" alt="男">
    <script>
        let img = document.querySelector('img');
        img.onclick = function() {
            if(img.title.lastIndexOf("男") != -1){
                img.src = 'female.png';
                img.title = '女';
            }else{
                img.src = 'male.png';
                img.title = '男';
            }
        }
    </script>

运行结果:

3.3 获取/修改表单元素属性

代码示例1: 播放 暂停的转换.

<input type="button" value="播放">
<script>
    let input = document.querySelector('input');
    input.onclick = function() {
        if(input.value == '播放'){
            input.value = '暂停';
        }else{
            input.value = '播放';
        }
    }
</script>

运行截图:

代码示例2: 计数

<input type="text" value="0" id="one">
    <input type="button" value="点击+1" id="add">
    <script>
        let one = document.querySelector('#one');
        let add = document.querySelector('#add');
        add.onclick = function() {
            one.value++;
        }
    </script>

代码示例3: 全选/取消全选按钮

<h3>选择你喜欢玩的游戏</h3>
    <input type="checkbox" class="game">王者荣耀<br/>
    <input type="checkbox" class="game">和平精英<br/>
    <input type="checkbox" class="game">开心消消乐<br/>
    <input type="checkbox" class="game">我的世界<br/>
    <input type="checkbox" class="all">全选
    <script>
        let games = document.querySelectorAll('.game');
        let all = document.querySelector('.all');
        all.onclick = function(){
            for (let i = 0; i < games.length; i++) {
                games[i].checked = all.checked;
            }
        }
        for (let i = 0; i < games.length; i++) {
            games[i].onclick = function() {
                all.checked = allChecked();
            }
        }

        function allChecked() {
            for (let i = 0; i < games.length; i++) {
                if(!games[i].checked){
                    return false;
                }
            }
            return true;
        }
    </script>

运行截图

3.4 获取/修改样式属性

CSS 中指定给元素的属性, 都可以通过 JS 来修改
style 中的属性都是使用 驼峰命名 的方式和 CSS 属性对应的.
例如: font-size => fontSize, background-color => backgroundColor

1. 行内样式操作

element.style.[属性名] = [属性值];
element.style.cssText = [属性名+属性值];
代码示例: 字体变大
<div style="font-size: 20px;color:red">你好</div>
    <script>
        let div = document.querySelector('div');
        div.onclick = function() {
            let fontSize = parseInt(div.style.fontSize);
            fontSize += 10;
            div.style.fontSize = fontSize + "px";//注意有单位的要带上单位
        }
    </script>

运行截图:

2. 类名样式操作

element.className = [CSS 类名];
代码示例: 背景颜色变化
<style>
        html,body{
            height: 100%;
            width: 100%;
        }
        div {
            height: 100%;
            width: 100%;
        }
        .black{
            background-color:black;
            color: gray;
        }
        .gray {
            background-color: gray;
            color: black;
        }
    </style>
    <div class='black'>
        你好!
    </div>
    <script>
        let div = document.querySelector('div');
        div.onclick = function() {
            if(div.className.indexOf("black") != -1){
                div.className = 'gray';
            }else{
                div.className = 'black';
            }
        }
    </script>

运行截图:

4. 操作节点

4.1 新增节点

分为两个步骤:

  1. 创建元素节点
    createElement创建元素节点.
    createTextNode 创建文本节点
    createComment 创建注释节点
    createAttribute 创建属性节点
  2. 插入节点到 dom 树中
    ① 使用 appendChild 将节点插入到指定节点的最后一个孩子之后
    ②使用insertBefore将节点插入到指定节点之前

代码示例:

<div class="test">

    </div>
    <script>
        let div = document.createElement('div');
        div.id = 'mydiv';
        div.className = 'one';
        div.innerHTML = 'hehe';

        let test = document.querySelector('.test');
        test.appendChild(div);
    </script>

运行截图:

代码示例: 当一个节点插入两次,相当于移动.

<div class="parent">
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
    </div>

    <script>
        let child = document.createElement('div');
        child.innerHTML = '100';

        let parent = document.querySelector('.parent');
        // 本来有四个元素,0号元素没有,就插入一个元素
        parent.insertBefore(child,parent.children[0]);
        // 插入到2号元素前,1号元素是1不是child,2号元素是2.
        parent.insertBefore(child,parent.children[2]);
    </script>

运行结果:

4.2 删除节点

使用 removeChild 删除子节点

oldChild = element.removeChild(child);

注: 如果 child 不是 element 的子节点,会抛异常

代码示例:

<div class="parent">
        <div class="child">1</div>
        <div class="child">2</div>
        <div class="child">3</div>
    </div>
    <script>
        let parent = document.querySelector('.parent');
        let childs = document.querySelectorAll('.child');
        parent.removeChild(childs[1]);
    </script>

运行结果:

5. 实现几个案例

5.1 猜数字

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>猜数字</title>
</head>
<body>
    <div class="parent">
        <div><input type="button" value="重新开始一局新游戏" class="again"></div>
        <div>
            请输入要猜的数字: <input type="text" class="guessNum"> <input type="button" value="猜" class="press">
        </div>
        <div>
            已经猜的次数: <span class="count">0</span>
        </div>
        <div>
            结果: <span class="result"></span>
        </div>
    </div>
    <script>
        let guessNum = document.querySelector('.guessNum');
        let press = document.querySelector('.press');
        let count = document.querySelector('.count');
        let result = document.querySelector('.result');

        let countCount = 0;
        let guessResult = Math.floor(Math.random()*100)+1;
        press.onclick = function(){
            countCount++;
            count.innerHTML = countCount;
            guessNumber = parseInt(guessNum.value);
            if(guessNumber == guessResult){
                result.innerHTML = '猜对了';
                result.style = 'color : red';
            }else if(guessNumber < guessResult){
                result.innerHTML = '猜小了';
                result.style = 'color : blue';
            }else{
                result.innerHTML = '猜大了';
                result.style = 'color : orange';
            }
        }

        let again = document.querySelector('.again');
        again.onclick = function() {
            guessResult = Math.floor(Math.random()*100)+1;
            countCount = 0;
            count.innerHTML = 0;
            guessNum.value = '';
            result.innerHTML ='';
        }
    </script>
</body>
</html>

运行截图:

5.2 表白墙

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表白墙</title>
</head>
<body>
    <div class="parent">
        <div id="wall">表白墙</div>
        <div id="remind">输入后点击提交,会将信息显示在表格中</div>
        <div class="one"><span class="two">谁:</span><input type="text" class="text"></div>
        <div class="one"><span class="two">对谁:</span><input type="text" class="text"></div>
        <div class="one"><span class="two">说什么:</span><input type="text" class="text"></div>
        <div class="one"><input type="button" value="提 交" class="press"></div>
    </div>
    
    <style>
        /* 去除浏览器默认样式 */
        * {
            margin: 0;
            padding: 0;
        }
        /* 设置总宽度 */
        .parent {
            width: 400px;
            margin: 0 auto;
        }
        /* 涉资表白墙样式 */
        #wall {
            font-size: 30px;
            font-weight: 700;
            text-align: center;
            margin: 5px;
        }
        /* 设置提示信息样式 */
        #remind{
            font-size:13px;
            text-align: center;
            color:gray;
            margin: 5px;
        }
        /* 设置弹性布局 */
        .one {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 40px;
        }
        /* 设置文字内容 */
        .two {
            width: 100px;
            line-height: 40px;
        }
        /* 设置输入框 */
        .one .text{
            width: 200px;
            height: 20px;
        }
        /* 提交按钮的设置 */
        .one .press{
            width: 304px;
            height: 40px;
            color:white;
            background-color: orange;
            border-radius: 5px;
            border: none;
        } 
        /* 设置鼠标点击的时候改变颜色 */
        .one .press:active{
            background-color: red;
        }
        /* 提交之和内容的设置 */
        .elem {
            text-align: center;
            
        }
    </style>
    <script>
        // 获取到输入框元素
        let texts = document.querySelectorAll('.text');
        // 获取到提交按钮元素
        let press = document.querySelector('.press');
        // 设置单击事件
        press.onclick = function() {
            let user1 = texts[0].value;
            let user2 = texts[1].value;
            let message = texts[2].value;
            // 如果有一个为空,就提交不成功
            if(user1=='' || user2=='' || message==''){
                return;
            }   
            // 这里都不为空,创建新的节点 
            let elem = document.createElement('div');
            elem.className = 'elem';
            elem.innerHTML = user1 + '对' + user2 + '说: ' +message;
            // 插入新的节点
            let parent = document.querySelector('.parent');
            parent.appendChild(elem);
            // 提交之后,将输入框置空.
            for(let i = 0; i < 3; i++){
                texts[i].value='';
            }
        }
    </script>
</body>
</html>

运行截图:

5.3 待办事项

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>待办事项</title>
</head>
<body>
    <div class="parent">
        <div class="one">
            <input type="text" class="text"><input type="button" value="新建任务" class="submit">
        </div>
        <div class="two">
            <div class="left">
                <h3>未完成</h3>
            </div>

            <div class="right">
                <h3>已完成</h3>
            </div>
        </div>
    </div>
    <style>
        /* 去除浏览器默认样式 */
        * {
            margin: 0;
            padding: 0;
        }
        /* 设置宽度 */
        .parent {
            width: 840px;
            margin: 0 auto;
        }
        /* 设置输入框和新建的样式 */
        .one {
            height: 50px;
            padding: 20px;
        }
        /* 设置输入框样式 */
        .one .text{
            height: 50px;
            width: 600px;
        }
        /* 设置提交框样式 */
        .one .submit {
            background-color: orange;
            color: white;
            height: 50px;
            width: 196px;
            border: none;
        }
        /* 设置点击时的背景 */
        .one .submit:active{
            background-color: red;
        }
        /* 设置已完成和未完成的样式 */
        .two{
            width: 800px;
            height: 800px;
            display: flex;
            margin: 0 auto;
        }
        /* 设置未完成和已完成字体样式 */
        .two h3 {
            height: 50px;
            text-align: center;
            line-height: 50px;
            background-color: black;
            color: white;
        }
        /* 设置未完成左边的样式 */
        .left {
            width: 50%;
            height: 100%;
        }
        /* 设置已完成右边的样式 */
        .right {
            width: 50%;
            height: 100%;
        }
        /* 新建任务的样式 */
        .row {
            height: 50px;
            display: flex;
            align-items: center;
        }
        /* 新建任务字体的样式 */
        .row span {
            width: 340px;
        }
        /* 新建任务的删除按钮样式 */
        .row button{
            width: 40px;
            height: 40px;
        }
    </style>
    <script>
        // 首先获取新建按钮元素
        let submit = document.querySelector('.submit');
        // 设置鼠标单击事件
        submit.onclick = function() {
            // 获取输入框元素
            let text = document.querySelector('.text');
            // 判断输入框内容是否为空
            if(text.value == '') return;
            // 新建代办事项
            let row = document.createElement('div');
            row.className='row';
            let checkBox = document.createElement('input');
            checkBox.type='checkbox';
            let thing = document.createElement('span');
            thing.innerHTML = text.value;
            let del = document.createElement('button');
            del.innerHTML='删除';
            row.appendChild(checkBox);
            row.appendChild(thing);
            row.appendChild(del);
            // 获取左边元素
            let left = document.querySelector('.left');
            left.appendChild(row);
            // 添加节点之后置空
            text.value='';

            // 设置选择框的鼠标单击事件
            checkBox.onclick = function() {
                // 如果被选择了就移动已完成
                // 如果未完成就移动到未完成
                if(checkBox.checked){
                    let target = document.querySelector('.right');
                    target.appendChild(row);
                }else{
                    let target = document.q
                    uerySelector('.left');
                    target.appendChild(row);
                }
            }
            // 设置删除按钮的鼠标单击事件
            del.onclick = function() {
                // 使用 parentNode 获取到父节点
                let parent = row.parentNode;
                // 删除该节点
                parent.removeChild(row);
            }
        }
    </script>
</body>
</html>

运行截图:

相关文章