Window对象与本地存储

103 阅读6分钟

Window对象

BOM

BOM(Browser Object Model ) 是浏览器对象模型

1649940669959

window 是浏览器内置中的全局对象,我们所学习的所有 Web APIs 的知识内容都是基于 window 对象实现的

window 对象下包含了 navigator、location、document、history、screen 5个属性,即所谓的 BOM (浏览器对象模型)

document 是实现 DOM 的基础,它其实是依附于 window 的属性。

注:依附于 window 对象的所有属性和方法,使用时可以省略 window

定时器-延时函数

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

语法:

1649940784328

setTimeout 仅仅只执行一次,所以可以理解为就是把一段代码延迟执行, 平时省略window

清除延时函数:

1649940813508

    <button>按钮</button>
    <script>
        const btn = document.querySelector('button')
        const btn1 = setTimeout(function(){
            console.log('这是关闭');
        }, 5000)
        btn.addEventListener('click',function(){
            clearInterval(btn1)
        })
    </script>

案例 5秒钟之后消失的广告

分析: ①:设置延时函数 ②:隐藏元素

    <div class="box">男人哭吧哭吧不是罪</div>
    <script>
        // 延时函数
        setTimeout(function(){
            // 直接设置输出这个标签的css样式
            document.querySelector('.box').style.display = 'none'
        }, 5000)
    </script>

结合递归函数可以使用 setTimeout 实现 setInterval 一样的功能

    <script>
        // 定时器 不主动清除 定时器永远会执行下去
        // 延时器只会执行一次
        // 用延时器实现定时器功能 在延时器身上又开启一个延时器
        // 使用递归 自己调用自己 就是函数自己调用自己

        // 设置一个数字为0
        let index = 0
        // 函数封装
        function func(){
            // 打印自己的数字输出 
            console.log(++index);
            // 使用延时器 在里面调用自己
            setTimeout(func, 500)
            // 初始为0 自增为1 然后使用延时器 延时器里又调用自己
            // 1再自增为2 然后延时器启用 再次调用自己 循环
        }
       func();
    </script>

两种定时器对比:

setInterval 的特征是重复执行,首次执行会延时

setTimeout 的特征是延时执行,只执行 1 次

setTimeout 结合递归函数,能模拟 setInterval 重复执行

clearTimeout 清除由 setTimeout 创建的定时任务

创建的定时器应该由clearInterval来清除

创建的延迟器应该由clrearTimeout来清除

JS 是单线程

JavaScript 语言的一大特点就是单线程,也就是说,同一个时间只能做一件事。这是因为 Javascript 这门脚本语言诞生的使命所致——JavaScript 是为处理页面中用户的交互,以及操作 DOM 而诞生的。比如我们对某个 DOM 元素进行添加和删除操作,不能同时进行。 应该先进行添加,之后再删除。

单线程就意味着,所有任务需要排队,前一个任务结束,才会执行后一个任务。这样所导致的问题是: 如果 JS 执行的时间过长,这样就会造成页面的渲染不连贯,导致页面渲染加载阻塞的感觉。

location对象

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

常用属性和方法:

href 属性获取完整的 URL 地址,对其赋值时用于地址的跳转

search 属性获取地址中携带的参数,符号 ?后面部分

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

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

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

常用属性和方法:

href 属性获取完整的 URL 地址,对其赋值时用于地址的跳转

1649943872435

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

常用属性和方法:

search 属性获取地址中携带的参数,符号 ?后面部分

1649943934545

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

1649943981680

后期vue路由的铺垫,经常用于不刷新页面,显示不同页面,比如 网易云音乐

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

1649944020931

    <button>跳转到百度</button>
    <script>
        // 1 使用a标签 href 属性 可以实现页面跳转
        // 2 在js中,也可以直接跳转  location.href 来跳转
        // 3 location.href 也可以实现刷新 location.href = location.href;
        // 4  location.reload(true);// true 强制刷新!
        // 5 search 后一个阶段就会用到它 了  获取 url上 ? 后面一串字符  /17-location.html?a=1&b=2
        // 6 hash 学习到了vue阶段就会用到了 获取 # 后面一串字符 /17-location.html#/index  #/index
        const button = document.querySelector('button')
        button.addEventListener('click', function(){
            // location.href = 'http://www.baidu.com' // 点击就跳转当指定的页面
            // console.log(location.href); // 如果没有指定跳转的页面 返回的是当前自己的网页
            // location.href = location.href // 刷新功能
            // reload 实现刷新
            // location.reload(true) // 强制刷新
            console.log(location.search)
        })
        // 延时 自动跳转当网页 (就像以前的弹窗广告)
        // setTimeout(function(){
        //     location.href = 'http://www.baidu.com'
        // }, 3000)
    </script>

navigator对象

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

常用属性和方法:

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

    <script>
        // 作用 检测当前浏览器的版本和型号
        console.log(window.navigator.userAgent);
    </script>
    <a href="#">下载软件</a>
    
    <script>
      // 作用 检测当前浏览器的版本和型号
      //  手机端来说,  安卓手机 可以直接下载apk 手机软件的 
      //               ios 手机来说 不可以直接下载手机软件 必须要回到苹果的应用商店中来下载
      // 安卓手机来说 点击 下载软件 给它下载apk
      // iphone手机来说 点击 下载软件 可能只需给苹果手机一个提示 


      // 可以识别出 当前的访问设备是 pc端还是移动端
      // 后台根据 当前用户的设备类型 来返回 对应的平台的页面
      // pc端来访问我的页面 我给你显示pc端的页面
      // 移动端来访问我的页面 我给你显示移动端的页面 
      // b站就是 


      // console.log(window.navigator.userAgent); 

      // 也是直接找别人写好的代码 检测即可 
      // 我也想自己去检测 花时间去截取和处理字符串  字符串方法 和 正则 

      // !(function () {
      //   const userAgent = navigator.userAgent;
      //   // 验证是否为Android或iPhone
      //   const android = userAgent.match(/(Android);?[\s\/]+([\d.]+)?/);
      //   const iphone = userAgent.match(/(iPhone\sOS)\s([\d_]+)/);
      //   // 如果是Android或iPhone,则跳转至移动站点
      //   // if (android || iphone) {
      //   //   location.href = 'http://m.itcast.cn';
      //   // }
      //   console.log(android);
      //   console.log(iphone);
      // })();
      validBrowser()
      function validBrowser() {
        var u_agent = navigator.userAgent;
        var browser_name = 'Failed to identify the browser';
        if (u_agent.indexOf('Firefox') > -1) {
          browser_name = 'Firefox';
        } else if (u_agent.indexOf('Chrome') > -1) {
          browser_name = 'Chrome';
        } else if (
          u_agent.indexOf('Trident') > -1 &&
          u_agent.indexOf('rv:11') > -1
        ) {
          browser_name = 'IE11';
        } else if (
          u_agent.indexOf('MSIE') > -1 &&
          u_agent.indexOf('Trident') > -1
        ) {
          browser_name = 'IE(8-10)';
        } else if (u_agent.indexOf('MSIE') > -1) {
          browser_name = 'IE(6-7)';
        } else if (u_agent.indexOf('Opera') > -1) {
          browser_name = 'Opera';
        } else {
          browser_name += ',info:' + u_agent;
        }
        document.write('browser_name:' + browser_name + '<br>');
        document.write('u_agent:' + u_agent + '<br>');
      }
    </script>

histroy对象

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

常用属性和方法:

1649944183345

history 对象一般在实际开发中比较少用,但是会在一些 OA 办公系统中见到

swiper插件

插件: 就是别人写好的一些代码,我们只需要复制对应的代码,就可以直接实现对应的效果

学习插件的基本过程

熟悉官网,了解这个插件可以完成什么需求 www.swiper.com.cn/

看在线演示,找到符合自己需求的demo www.swiper.com.cn/demo/index.…

查看基本使用流程 www.swiper.com.cn/usage/index…

查看APi文档,去配置自己的插件 www.swiper.com.cn/api/index.h…

注意: 多个swiper同时使用的时候, 类名需要注意区分

本地存储

本地存储特性

随着互联网的快速发展,基于网页的应用越来越普遍,同时也变的越来越复杂,为了满足各种各样的需求,会经常性在本地存储大量的数据,HTML5规范提出了相关解决方案。

1、数据存储在用户浏览器中

2、设置、读取方便、甚至页面刷新不丢失数据

3、容量较大,sessionStorage和localStorage约 5M 左右

localStorage

1、生命周期永久生效,除非手动删除 否则关闭页面也会存在

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

3、以键值对的形式存储使用

本地存储 四个常用api

​ 1 存 localStorage.setItem('属性名', 属性值)

​ 2 取 localStorage.getItem('属性名')

​ 3 删除一个 localStorage.removeItem('属性名')

​ 4 清空 localStorage.clear()

存储复杂数据类型存储

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

JSON.stringify(复杂数据类型)

将复杂数据转换成JSON字符串 存储 本地存储中

JSON.parse(JSON字符串)

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

语法演示

    <button>按钮</button>
    <script>
        const button = document.querySelector('button')
        button.addEventListener('click',function(){
            document.body.style.backgroundColor = 'aqua'
            // 储存数据 localStorage.setItem('属性名', 属性值)
            localStorage.setItem('num', 20)
            // // 获取数据 localStorage.getItem('属性名')
            // let result = localStorage.getItem('num')
            // console.log(result);
            // 删除数据 localStorage.removeItem('属性名')
            localStorage.removeItem('num')
        })
        // 复杂类型转字符串存储  因为本地储存可以储存简单类型 复杂不行 需要加引号
        let obj = "{name:'ls', age:18}"
        console.log(obj);
        localStorage.setItem('obj', obj)


        let obj1 = {name:'张三', age:18}
        // 更简单
        let result1 = JSON.stringify(obj1)
        console.log(result1);
        // localStorage.setItem('obj1', result1)
        localStorage.setItem('obj1', JSON.stringify(obj1))
        // 转回复杂数据类型
        console.log(JSON.parse(result1));
        
        // 本地存储 四个常用api
        // 1 存 localStorage.setItem('属性名', 属性值)
        // 2 取 localStorage.getItem('属性名')
        // 3 删除一个 localStorage.removeItem('属性名')
        // 4 清空 localStorage.clear()
    </script>

案例 页面刷新保留颜色

    <button>按钮</button>
    <script>
        const button = document.querySelector('button')
        button.addEventListener('click',function(){
            document.body.style.backgroundColor = 'aqua'
            // 储存数据 localStorage.setItem('属性名', 属性值)
            const color = 'aqua'
            document.body.style.backgroundColor = color
            localStorage.setItem('color', 'aqua')
            
        })
        document.body.style.backgroundColor = localStorage.getItem('color')
        
        // button.addEventListener('click',function(){
        //     document.body.style.backgroundColor = 'aqua'
        //     localStorage.setItem('button', `${document.body.style.backgroundColor}`)
        // })
        // document.body.style.backgroundColor = localStorage.getItem('button')
    </script>

自定义颜色选择 让刷新之后颜色保留使用

    <input type="color">
    <script>
        const colorInput = document.querySelector('input')
        // 代码重新执行 页面刷新
        document.body.style.backgroundColor = localStorage.getItem('bgcolor')
        colorInput.addEventListener('click',function(){
            document.body.style.backgroundColor = this.value
            // 设置颜色存储到本地中
            localStorage.setItem('bgcolor', this.value)
        })
    </script>

学生信息表录入 ---js

需求:改为本次存储版本的学习信息表

分析:

需求①:读取本地存储数据(封装函数)

如果本地存储有数据,则返回 JSON.parse() 之后的对象

如果本地存储没有数据,则默认写入三条数据,注意存储的利用JSON.stringify() 存 储JSON 格式的数据

需求②:渲染模块

先读取本地存储数据,然后渲染

需求③:添加模块

注意,先取的最新的本地存储数据,然后追加 新增了数据,要把新数据存储到本地存储,别忘记转换

    <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>
      </tbody>
    </table>
    <script>
        // 1.1 定义数组 负责存放表格要显示的数据
        let arr = [ ];
        // strArr = 获取的数据
        const strArr = localStorage.getItem('arr')
        if(strArr){
          // 有数据 就将字符串转数组
          arr = JSON.parse(strArr)
        }else{
          // 没有就空数组
          arr = []
        }

        const tbody = document.querySelector('tbody');
        // 2  给 录入绑定点击事件
        const add = document.querySelector('.add');
        const uname = document.querySelector('.uname');
        const age = document.querySelector('.age');
        const gender = document.querySelector('.gender');
        const salary = document.querySelector('.salary');
        const city = document.querySelector('.city');
  
        // 1.2 根据数组渲染页面
        renderTableByArr();
  
        // 2  按钮绑定点击事件
        add.addEventListener('click', function () {
          // 2.1 创建一个新的对象 把表单数据都合并到对象中
          const data = {
            // 学号
            id: Date.now(),
            // 姓名
            uname: uname.value,
            // 年龄
            age: age.value,
            // 性别
            gender: gender.value,
            // 薪资
            salary: salary.value,
            // 就业城市
            city: city.value,
          };
  
          // 可以 用断点来测试 上面的代码有没有写错
          // 2.2 给数组插入新的元素
          arr.push(data);

          // 把数组转成字符串
          const strArr = JSON.stringify(arr)
          // 存一份到本地存储中
          localStorage.setItem('arr', strArr)

          // 2.3 数组发生改变  重新调用渲染页面的函数
          renderTableByArr();
  
          // 2.4 表单数据清空
          uname.value = '';
          age.value = '';
          gender.value = '男';
          salary.value = '';
          city.value = '北京';
        });
  
        // 3 tbody绑定点击事件,同时判断被点击的是不是 del 删除标签
        tbody.addEventListener('click', function (event) {
          // 3.1 判断当前点击的是不是a标签
          if (event.target.nodeName === 'A') {
            // <a data-index="2" href="javascript:" class="del">删除</a>
  
            // 获取到a标签 上存放的 index
            // event.target =  a标签的dom元素
            // console.dir(event.target.dataset.index)
            const index = event.target.dataset.index;
  
            // 3.3 执行数组删除元素
            arr.splice(index,1);

            // 把数组转成字符串
            const strArr = JSON.stringify(arr)
            // 存一份到本地存储中
            localStorage.setItem('arr', strArr)


            // 3.4 调用根据数组渲染页面的函数 
            renderTableByArr();
          }
        });
        // 根据数组渲染表格
        function renderTableByArr() {
          let html = ``;
          for (let index = 0; index < arr.length; index++) {
            html += `
           <tr>
            <td>${arr[index].id}</td>
            <td>${arr[index].uname}</td>
            <td>${arr[index].age}</td>
            <td>${arr[index].gender}</td>
            <td>${arr[index].salary}</td>
            <td>${arr[index].city}</td>
            <td>
              <a data-index="${index}" href="javascript:" class="del">删除</a>
            </td>
          </tr>
           `;
          }
  
          // 把生成的tr插入到 tbody中
          tbody.innerHTML = html;
        }
      </script>

学生信息表录入 ---css

* {
    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;
  }

sessionStorage(了解)

1、生命周期为关闭浏览器窗口

2、在同一个窗口(页面)下数据可以共享

3、以键值对的形式存储使用

4、用法跟localStorage 基本相同

    <script>
        //本地存储的技术 sessionStorage 会话(打开页面到关闭页面之间过程 一次会话 ajax node)存储 
        // 登录的时候
        // 它的用法和 localstorage 用法一样区别只有一个
        // sessionStorage 关闭页面后 数据就丢失
        // localstorage 除非是用户主动删除 否则一直存在 直到天荒地老
        // 存数据
        sessionStorage.setItem('ss', 123)
        // 取数据
        console.log(sessionStorage.getItem('ss'));
        // 删除一个
        sessionStorage.removeItem('ss')
        // 清空
        sessionStorage.clear()
    </script>

自定义属性

固有属性:

标签天生自带的属性 比如class id title等, 可以直接使用点语法操作

自定义属性:

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

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

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

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

1650031062659

data-自定义属性:

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

1650031098475

    <a data-index="0" id="nav" href="http://www.baidu.com" hello="no" aa="bb" >跳转</a >

    <script>
      // 获取 dom元素的固有属性  通过点语法来获取
      const a = document.querySelector('a');
      // 获取固有属性
      // console.log(a.href);
      // console.log(a.id);

      // 直接修改
      // a.href="http://www.qq.com";
      // a.id="top";

      // 自定义属性 不能直接通过点语法来获取和设置
      // 获取 getAttribute("属性名")
      // console.log(a.hello);
      // console.log(a.aa);
      // console.log( a.getAttribute("hello") );
      // console.log( a.getAttribute("aa") );

      // 设置 setAttribute(key,value)
      // a.setAttribute("hello","123");

      // 删除掉属性 removeAttribute(key)
      // a.removeAttribute("hello");

      //  自定义属性 -> h5建议的 自定义属性
      // 属性的时候 data-xxx 开头
      //  获取的时候  a.dataset.xxx
      //  设置  a.dataset.index = 3;

      // console.log(a.dataset.index);
      // a.dataset.index = 3;

      /* 
      
      小结 
      标签的属性 有两种分为
      1 固有属性  比如 id href src     点语法的方式获取和设置 方便
      2 自定义属性
        1 随机自己瞎命名  
          <a  abc="123" >  
            获取 (getAttribute) 设置 setAttribute(key,value)  删除   removeAttribute(key)
        2 h5建议 data- xxx
          <a  data-abc="123" >  
            获取(a.dataset.abc)  设置(a.dataset.abc=456);
      3 最强大是  (getAttribute)  setAttribute removeAttribute 
            上述的这个方式,可以获取到任意的属性(固有属性和h5建议的自定义属性)
            <a data-index="0" id="nav" href="http://www.baidu.com" hello="no" aa="bb" >跳转</a >
      */
    //  console.log( a.getAttribute("data-index") );
    //  console.log( a.getAttribute("id") );
    //  console.log( a.getAttribute("href") );
    //  console.log( a.getAttribute("hello") );
    //  console.log( a.getAttribute("aa") );
    </script>
    <ul></ul>
    <script>
        // 根据数组 渲染出li标签 点击li标签的时候  根据它对应的颜色 设置到 我body标签背景中
        // 数组
        let arr = [
            { price: '100', title: '去旅游', color: 'yellow' },
            { price: '200', title: '去读书', color: 'red' },
            { price: '300', title: '去吃饭', color: 'blue' },
        ];
        const uls = document.querySelector('ul')
        let html =``
        for (let index = 0; index < arr.length; index++) {
            html += `
            <li data-price="${arr[index].price}" data-color ="${arr[index].color}">${arr[index].title}</li>
            `;
        }
        uls.innerHTML = html
         // 事件委托
        uls.addEventListener('click', function(event){
            if(event.target.nodeName === 'LI'){
                // 设置body标签的背景颜色  等于什么  =  等于当前被点击的元素(li) 身上的自定义属性 data-color
                // document.body.style.backgroundColor = event.target.dataset.color

                // 换一种方式写
                document.body.style.backgroundColor = event.target.getAttribute('data-color')
                // alert(`你想要去做的事情,要花这么多钱哦 ${event.target.dataset.price}`)
            }
        })
    </script>