BOM-操作浏览器

403 阅读5分钟

一、Window对象

1.BOM

  • BOM是浏览器对象模型

image-20220414230212778

  • Window 是浏览器内置中的全局对象 ,我们所学习的所有web APIs 知识内容都是基于Window对象实现的
  • window 对象下包含了 navigator、location、document、history、screen 5个属性,即所谓的 BOM (浏览器对象模型)
  • document 是实现 DOM 的基础,它其实是依附于 window 的属性。
  • 注:依附于 window 对象的所有属性和方法,使用时可以省略 window

2.定时器-延时器

2.1介绍:JavaScript内置的一个用来让代码延迟执行的函数,叫setTimeout

2.2 常用场景:关闭广告

image-20220414160855187

2.3关闭广告案例

    <title>延时器-广告</title>
    <style>
      .box {
        width: 200px;
        height: 200px;
        background-color: rgb(170, 212, 88);
        border-radius: 5px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
      }
    </style>
  </head>
  <body>
    <div class="box">持久不掉妆,就用雅诗兰黛</div>
    <script>
      setTimeout(function () {
        document.querySelector(".box").style.display = "none";
      },5000);
    </script>
  </body>

2.4清除延时函数

image-20220414230558091

2.5 延时器和定时器的区别

image-20220414230953025

3.location对象

  • location的数据类型的对象,它拆分并保存了URL地址各个组成部分

  • 常用属性和方法

    href 属性获取完整的 URL 地址,对其赋值时用于地址的跳转 search 属性获取地址中携带的参数,符号 ?后面部分

    image-20220416113826260

    hash 属性获取地址中的啥希值,符号 # 后面部分

    image-20220416114354031reload 方法用来刷新当前页面,传入参数 true 时表示强制刷新

    <body>
        <button>跳转到百度</button>
        <script>
          const button = document.querySelector("button");
          button.addEventListener("click", function () {
            // location.href = ''
         
            // 刷新功能
            // location.href =  location.href
            // reload实现刷新
            // location.reload(true); //强制刷新
            console.log(location.search);
            console.log(location.hash);
          });
        setTimeout(function () {
            location.href = 'http://baidu.com'
          },5000)
        </script>
      </body>
    

4.navigatior 对象

  • navigatior 的数据类型是对象,该对象下记录了浏览器自身的相关信息

  • 常用属性和方法

    通过 userAgent 检测浏览器的版本及平台

    image-20220415235433757

5.histroy对象

  • histroy的数据类型是对象,该对象与浏览器地址栏的操作相对应,如前进,后退,历史记录等

  • image-20220416001312256

      <body>
        <a href="http://www.baidu.com">百度</a>
        <button class="forward">前进</button>
        <button class="back">后退</button>
        <script>
          const forward = document.querySelector('.forward')
          forward.addEventListener('click',function () {
            history.forward()
          })
          const back = document.querySelector('.back')
          back.addEventListener('click',function () {
            history.back()
          })
        </script>
      </body>
    

6.递归

1.定义 :一个函数调用自己

2.使用场景:

​ 有一个函数,可以打印出一个dom元素的所有祖先元素

​ 不可能提前知道,这个a 标签有多少个父元素

​ 这个函数接收一个参数 =dom,如果这个dom元素有父元素,就继续调用自己函数

二、swiper 插件

作用:使用别人写好的轮播图代码,直接复制使用就可以了比较高效方便

(选择swiper7安装包)

swiper 使用方法:www.swiper.com.cn/usage/index…

image-20220415160007758

操作步骤

  1. 下载swiper对应的文件 -CSS+js

  2. 分别引入他们

  3. 拷贝别人的固定结构

  4. 拷贝写好的swiper初始化js代码

三、本地存储

1.localStorage

特性

  • 数据存储在用户浏览器中
  • 设置读取比较方便,甚至页面刷新了,数据还在
  • 容量比较大,localStorage和sessionStorage约5M左右

特点

  • 生命周期永久生效,除非手动删除,否则关闭页面数据还是会存在的

  • 可以多个窗口(页面)共享(同一个浏览器可以共享)

  • 以键值对的形式存储使用

    image-20220416115604061

    语法

    存储数据

    localStorage.setItem(key,value)

    获取数据

    localStorage.getItem(key)

    删除数据

    localStorage.removeItem(key);

    清空所有

    localStorage.clear()

页面换肤案例

 <title>页面换肤功能</title>
</head>
<body>
  <input type="color">
  <script>
    // 代码重新执行,,页面刷新,获取本地存储的颜色
    document.body.style.backgroundColor = localStorage.getItem('backgroundColor')
    const colorInput = document.querySelector('input')
    // 需要给这个标签 绑定change事件,选好了值之后,就会触发的一个事件
    colorInput.addEventListener('change',function () {
      // 通过value 属性来获取选中的颜色
      console.log(this.value);
      document.body.style.backgroundColor = this.value
      // 设置颜色存储到本地页面中
      localStorage.setItem('backgroundColor',this.value)
    })
    
  </script>
</body>

存储复杂数据类型存储

作用:本地只能存储字符串,无法存储复杂数据类型,需要将复杂数据类型转成JSON字符串,在存储到本地

JSON.stringify(复杂数据类型)

将复杂数据类型转成JSON字符串,存储在本地存储中

JSON.parse(JSON字符串)

将JSON字符串转换成对象, 取出时候使用

    <title>存储复杂数据类型存储</title>
  </head>
  <body>
    <script>
      // 复杂类型数据
      const obj = { name: "路飞", height: 170, weight: 100 };
      // 先将对象转成字符串
      const objStr = JSON.stringify(obj)
      //再把转成字符串的数据存储起来
      localStorage.setItem('obj',objStr)
      // 把本地存储的数据重新读取出来
      const newObjStr = localStorage.getItem('obj')
      console.log(newObjStr);
      // 最后再把字符串解析回原来的对象
      const newObj= JSON.parse(newObjStr)
      console.log(newObj);
    </script>
  </body>

学生就业薪资案例

解题思路分析

image-20220416153509605

<!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>学生信息综合案例</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      a {
        text-decoration: none;
        color: #721c24;
      }
      h1 {
        text-align: center;
        color: #333;
        margin: 20px 0;
      }
      table {
        margin: 0 auto;
        width: 800px;
        border-collapse: collapse;
        color: #004085;
      }
      th {
        padding: 10px;
        background: #cfe5ff;

        font-size: 20px;
        font-weight: 400;
      }
      td,
      th {
        border: 1px solid #b8daff;
      }
      td {
        padding: 10px;
        color: #666;
        text-align: center;
        font-size: 16px;
      }
      tbody tr {
        background: #fff;
      }
      tbody tr:hover {
        background: #e1ecf8;
      }
      .info {
        width: 900px;
        margin: 50px auto;
        text-align: center;
      }
      .info input {
        width: 80px;
        height: 25px;
        outline: none;
        border-radius: 5px;
        border: 1px solid #b8daff;
        padding-left: 5px;
      }
      .info button {
        width: 60px;
        height: 25px;
        background-color: #004085;
        outline: none;
        border: 0;
        color: #fff;
        cursor: pointer;
        border-radius: 5px;
      }
      .info .age {
        width: 50px;
      }
    </style>
  </head>

  <body>
    <h1>新增学员</h1>
    <div class="info">
      姓名:<input type="text" class="uname" /> 年龄:<input
        type="text"
        class="age"
      />
      性别:
      <select name="gender" id="" class="gender">
        <option value="男"></option>
        <option value="女"></option>
      </select>
      薪资:<input type="text" class="salary" /> 就业城市:<select
        name="city"
        id=""
        class="city"
      >
        <option value="北京">北京</option>
        <option value="上海">上海</option>
        <option value="广州">广州</option>
        <option value="深圳">深圳</option>
        <option value="曹县">曹县</option>
      </select>
      <button class="add">录入</button>
    </div>

    <h1>就业榜</h1>
    <table>
      <thead>
        <tr>
          <th>学号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>薪资</th>
          <th>就业城市</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- <tr>
          <td>1</td>
          <td>这是名称</td>
          <td>这是年龄</td>
          <td>这是性别</td>
          <td>这是工资</td>
          <td>这是所在城市</td>
          <td>
            <a href="javascript:" class="del">删除</a>
          </td>
        </tr> -->
      </tbody>
    </table>
    <script>
      // 打开页面,获取本地存储的数据
      const strArray = localStorage.getItem("array");
      /*  需求:添加数据,删除数据 */
      // 1.1设置一个数组,对象存放表格要显示的数据  方便管理
      let array = [];
       // 判断有有没有数据
       if (strArray) {
        // 有 就转回数组
        array = JSON.parse(strArray)
      } else {
        // 没数据 生成空数组
        array = []
      }
      // 2.给录入 绑定点击事件
      // 获取录入
      let button = document.querySelector(".add");
      // 获取tbody
      let tbody = document.querySelector("tbody");
      // 获取姓名
      let uname = document.querySelector(".uname");
      // 获取年龄
      let age = document.querySelector(".age");
      // 获取性别
      let gender = document.querySelector(".gender");
      // 获取薪资
      let salary = document.querySelector(".salary");
      // 获取城市
      let city = document.querySelector(".city");

      // 1.3调用渲染页面的函数
      renderByArr();

      // 2.给按钮注册事件
      button.addEventListener("click", function () {
        // 2.1把表单数据合并到一个新的对象中
        let newDate = {
          // 随机生成时间,时间戳
          num: +new Date(),
          uname: uname.value,
          age: age.value,
          gender: gender.value,
          salary: salary.value,
          city: city.value,
        };
        // 2.2给数组新增对象数据
        array.push(newDate);
        // 先把数组转换成字符串类型
        const strArray = JSON.stringify(array);
        // 再把转成的字符串数据存储起来
        localStorage.setItem("array", strArray);
        // 2.3数组发生改变后,重新调用渲染页面
        renderByArr();
        // console.log(array);
        // 2.4点击发布后数据清零
        uname.value = "";
        age.value = "";
        gender.value = "男";
        salary.value = "";
        city.value = "北京";
      });
      // 删除数据
      // 3.tbody绑定点击事件,同时判断被点击的是不是删除标签
      tbody.addEventListener("click", function (event) {
        // 3.1 事件触发了先判断当前点击的是不是删除
        if (event.target.nodeName === "A") {
          // date-index 自定义属性
          // 3.2  在点击删除标签的时候,知道当前点击的是第几个元素
          // <a  date-index = '2' href="javascript:" class="del">删除</a>
          // 获取到a标签上的存放的index
          const index = event.target.dataset.index;
          // 3.3数组删除元素
          array.splice(index, 1);
          // 先把数组转换成字符串类型
          const strArray = JSON.stringify(array);
          // 再把转成的字符串数据存储起来
          localStorage.setItem("array", strArray);
          // 3.4数组发生改变后,重新调用渲染页面
          renderByArr();
        }
      });

      // 1.1根据数组渲染表格
      function renderByArr() {
        // 拼接开头
        let html = ``;
        for (let index = 0; index < array.length; index++) {
          html += `<tr>
          <td>${array[index].num}</td>
          <td>${array[index].uname}</td>
          <td>${array[index].age}</td>
          <td>${array[index].gender}</td>
          <td>${array[index].salary}</td>
          <td>${array[index].city}</td>
          <td>
            <a  date-index${index} href="javascript:" class="del">删除</a>
          </td>
        </tr>`;
        }
        // 把生成的tr插入到tbody中
        tbody.innerHTML = html;
      }
    </script>
  </body>
</html>

总结:只要使用了对象,不管是新增还是删除,都是需要转换成字符串存储在本地存储中

2.sessionStorage(了解)

特点

  • 生命周期为关闭浏览器窗口
  • 在同一个窗口(页面)下数据可以共享
  • 以键值对的形式存储使用
  • 和localStorage用法基本相同

语法

存储数据

sessionStorage.setItem((key,value))

获取数据

sessionStorage.getItem((key)

删除数据

sessionStorage.removeItem((key)

清空数据

sessionStorage.clear()

总结两者区别

localStorage 永久存储 除非手动删除

sessionStorage 关闭浏览器消失不见

四、元素属性

1.固有属性

比如id,href src,点语法的方式获取和设置,会比较方便

image-20220415121052576

<body>
  <a id="11" href="http://www.baidu.com">跳转</a>
  <script>
    const a = document.querySelector('a')
    // 元素固有属性,可以通过点语法来获取到
    console.log(a.id);
    console.log(a.href);
    // 可以通过点语法来设置到
    a.id= '22'
    a.href='http://www:qq.com'
  </script>
</body>

2.自定义属性

2.1随机自己命名的

这种方式最强大,可以获取到任意的属性 - (固有数据和h5 建议的自定义属性都可以

由程序员自己添加的属性,在DOM对象中找不到,无法使用点语法操作,必须使用专门的API

获取自定义属性 getAttribute ('属性名')

设置自定义属性 setAttribute('属性名','属性值')

删除自定义属性 removeAttribute('属性名')

  <body>
    <a aa="bb" hello="yes" id="11" href="http://www.baidu.com">跳转</a>
    <script>
      const a = document.querySelector("a");
      // 自定义属性的 不能直接通过点属性来获取和设置
      // 获取getAttribute('属性名')
      console.log(a.getAttribute("hello"));
      console.log(a.getAttribute("aa"));
      // 设置 setAttribute(key,value)
      a.setAttribute('hello','123')
      a.setAttribute('aa','啊啊')
      // 删除掉属性 removeAttribute(key)
      a.removeAttribute('aa')
    </script>
  </body>

2.2 data-自定义属性

传统的自定义属性没有专门的定义规则,开发者随意定值,不够规范,所以在html5中推出来了专门的data-自定义属性。在标签上一律以data开头

  • 属性以data-xxx 开头
  • 获取的时候 a.dataset.xxx
  • 设置 a.dataset.index = 3

  <body>
    <a  data-index ="0"  aa="bb" hello="yes" id="11" href="http://www.baidu.com">跳转</a>
    <script>
      const a = document.querySelector("a");
      // 自定义属性-> h5 建议的 自定义属性
      // 属性的时候 data-xxx 开头
      // 获取的时候 a.dataset.xxx
      // 设置 a.dataset.index = 3
      console.log(a.dataset.index);
      a.dataset.index = 3
    </script>
  </body>

五、补充知识

  1. console.log(),里面变量不需要加引号,输入文字内容,就需要加引号因为里面是字符串所以需要使用要加引号

  2. console.log()打印输出是标签格式,而不是对象,console.dir()是打印输出对象格式

  3. 属性和方法的区别

    1.属性的获取和使用,不需要加括号;而方法需要加括号

    2.利用编辑器来区分:属性是矩形的,英语单词是property ;而方法是正方体 ,英语单词是method

    image-20220415160035152

  4. 字符串方法

    转大写: toUpperCase()

    转小写:toLowerCase()

    字符串转数组 split('') 注意要加上引号

      <body>
        <script>
          let msg = "HELLO";
          // 转大写  msg.toUpperCase()
          //  console.log( msg.toUpperCase());
          //  转小写 msg.toLowerCase()
          console.log(msg.toLowerCase());
          // 字符串转数组 split('')
          let str = "abcdef";
          console.log(str.split(''));
          let str1 = "a-b-c-d-e-f";
          console.log(str1.split('-'));
        </script>
      </body>
    

    5.数组方法

    ​ 数组转字符串 join("")

    ​ 数组连接 A.concat(B)

  <body>
    <script>
      // 数组转字符串
      const arr = ["a", "b", "c", "d"];
      console.log(arr.join(""));
      console.log(arr.join("-"));
      //  数组连接
      const arr1 = ["a", "b", "c", "d"];
      const arr2 = ["1", "2", "3", "4"];
      console.log(arr1.concat(arr2));
      // 字符串连接
      const str1 = "abcdef";
      const str2 = '123456'
      // console.log(str1.concat(str2)); //这种方式会比较少用
     console.log(str1 + str2); //这种会比较常用
    </script
  </body>

6.绑定事件和取消事件

  • addEventListener可以绑定多个同名事件
  • removeEventListener 可以取消对应事件类型和事件处理函数
  • 无法取消 addEventListener 事件对应匿名函数
    <title>绑定事件和取消事件</title>
  </head>
  <body>
    <button>开启问好</button>
    <script>
      const button = document.querySelector("button");

      function func1() {
        console.log("你好");
      }

      function func2() {
        console.log("我也好");
      }
      function func3() {
        console.log("大家好");
      }
      // 绑定事件
      button.addEventListener("click", func1);
      // addEventListener可以绑定多个同名事件
      button.addEventListener("click", func2);
      button.addEventListener("click", func3);
      
	    // 延时器,延时5秒才触发事件
      setTimeout(function () {
        //  取消这个事件绑定
        button.removeEventListener("click", func2);
      }, 5000);
    </script>
  </body>