WebAPI4-7

103 阅读4分钟

第四节

事件对象

也是个对象,这个对象里有事件触发时的相关信息//例如:鼠标点击事件中,事件对象就存了鼠标点在哪个位置等信息

在事件绑定的回调函数的第一个参数就是事件对象 //一般命名为event、ev、e

<body>
    <button>我是按钮</button>
    <script>
      const button = document.querySelector('button')
      button.addEventListener('click',function(e){
      console.log(e); //存放点击事件触发一瞬间信息,鼠标的位置
      })
    </script>
</body>

事件对象属性

<body>
    <div>点击点击</div>
    <script>
          const div = document.querySelector('div')
          div.addEventListener('click',function(e){
             e.type //获取事件的类型是:click
             e.clientX //鼠标X轴的位置,是相对于页面的位置
             e.clientY //鼠标Y轴的位置,是相对于页面的位置
             e.offsetX //相对于被绑定元素自身的位置
             e.offsetY //相对于被绑定元素自身的位置
          })
    </script>
</body>

案例-图片跟随鼠标移动

<style>
        img{
            width: 50px;
            height: 50px;
          
        }
        body{
            height: 1920px;
            cursor: none;
        }
    </style>
</head>
<body>
    <img src="./d8e9365a514f726aee132892e615a89.png" alt="">
    <script>
        //鼠标移动。小天使移动
        //获取鼠标的位置
        let img = document.querySelector('img')
        document.body.addEventListener('mousemove',function(e){
            let num1 = e.clientX
            let num2 = e.clientY
           
            img.style.transform = `translate(${num1}px,${num2}px)`
        })
    </script>
</body>
</html>

案例-微博按Enter键发布

<body>
     <h2>你有什么想说的</h2>
     <textarea  cols="40" rows="20"></textarea>
     <button>发布</button>
     <ul>

     </ul>
    <script>
       let ul = document.querySelector('ul')
       let button = document.querySelector('button')
       let textarea = document.querySelector('textarea')

        button.addEventListener('click',function(e){
            //判断里面的内容是否为空
            if (textarea.value.trim() === '') {
        
          return;
        }
            let li = document.createElement('li')
            li.innerText = textarea.value
            ul.appendChild(li)


           
            textarea.value = ''


        }) 
       

        textarea.addEventListener('keydown',function(e){
         if(e.key === 'Enter'){
            button.click() //给button按钮绑定过点击事件,也是可以主动触发的
            //这样就相当于点击了按钮
         }
              
        })
             

    </script>
</body>

第五节

事件流

事件流指的是事件完整执行过程中的流动路径 :事件捕获 -事件冒泡-目标阶段

事件捕获

捕获阶段是 从父到子

事件冒泡

当一个元素触发事件后,会依次向上调用所有父级元素的同名事件

冒泡阶段是从子到父,事件流方向默认是冒泡

1649725440518.png

目标阶段

最底层元素触发事件,就叫目标阶段

<body>
    <div class="yeye"><div class="father"><div class="son"></div>
        </div>
    </div>
    <script>
        const yeye = document.querySelector('.yeye')
        const father = document.querySelector('.father')
        const son = document.querySelector('.son')
        yeye.addEventListener('click',function(){
            console.log('a');
        },false)
        father.addEventListener('click',function(){
            console.log('b');
        },true)
        son.addEventListener('click',function(){
            console.log('c');
        },true)
       //默认是冒泡 false,点击son输出是:c,b,a
       //在函数后面 添加 true,则是捕获方向 a,b,c
       //谁用false,谁排在后面
    </script>
</body>

阻止事件冒泡

<body>
    <p>1</p>
    <div class="yeye"><div class="father"><div class="son"></div>
        </div>
    </div>
    <script>
        const yeye = document.querySelector('.yeye')
        const father = document.querySelector('.father')
        const son = document.querySelector('.son')
        const p = document.querySelector('p')
        yeye.addEventListener('click',function(){
            p.innerText = +(p.innerText) + 1
        })
        father.addEventListener('click',function(e){
            p.innerText = +(p.innerText) + 10
            e.stopPropagation()
        })
        son.addEventListener('click',function(e){
            p.innerText = +(p.innerText) + 100
            e.stopPropagation() //阻止事件冒泡
        })
      //e.stopPropagation(),谁添加。谁发生事件时,它的父级(包括爷爷以上)就不会再执行
    </script>
</body>

拓展知识-阻止默认行为

<body>
    <!-- a标签的href默认跳转功能/在form表单里面的button点击会刷新页面/还有表单的submit,提交就会刷新页面 -->
    <a href="">跳转</a>  
    <!-- 方法一:直接不要 href ,就可以避免跳转-->
    <form >
        <!-- 方法一: 直接把button移出form表单-->
        <!-- 方法二: 给button添加type="button"-->
       <button type="button">点击我</button>
       <!-- 方法三: 换成input 标签 type="button"-->
       <input type="button">
   
    </form>
    <script>
       const a = document.querySelector('a')
       const button = document.querySelector('button')
       const form = document.querySelector('form')
       //方法四:给事件添加event.preventDefault()
       a.addEventListener('click',function(event){
        event.preventDefault()
       })
       button.addEventListener('click',function(event){
        event.preventDefault()
       })
       form.addEventListener('submit',function(event){
        event.preventDefault()
       })

    </script>
</body>

案例-鼠标右键自定义菜单

 <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      body {
        height: 100vh;
      }
      ul{
          list-style: none;
          width: 100px;
          border-radius: 10px;
          padding-left: 10px;
          padding-right: 10px;
          border: 1px solid #ccc;
          display: none;
      }
      li{
          height: 40px;
          line-height: 40px;
          border-bottom: 1px solid #ccc;
          
      }
      li:last-child{
          border-bottom: none;
      }
      li:hover{
          background-color: rgb(111, 103, 235);
      }
    </style>
  </head>
  <body>
   <ul>
       <li>添加图标</li>
       <li>切换壁纸</li>
       <li>下载壁纸</li>
       <li>设置</li>
   </ul>
    <script>
     const ul = document.querySelector('ul')
     const body = document.querySelector('body')

     //contextmenu
     body.addEventListener('contextmenu',function(event){
        event.preventDefault()
        ul.style.display = 'block'
       let num1 = event.clientX
       let num2 =  event.clientY
       ul.style.transform = `translate(${num1}px,${num2}px)`
     })
     body.addEventListener('click',function(event){
     
        ul.style.display = 'none'
       
     })


    </script>

事件委托

事件委托是利用事件流的特征解决一些开发需求的知识技巧

优点:给父级元素加事件(可以提高性能) 原理:事件委托其实是利用事件冒泡的特点, 给父元素添加事件,子元素可以触发 实现:事件对象.target 可以获得真正触发事件的元素

<body>
    <ul>
        <li><a href="">1</a></li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
    <script>
        //利用冒泡原理,委托给父元素去执行,点击ul,因为ul里面包含了li ,但是点击ul里面的任何东西都可以执行
        const ul = document.querySelector('ul')
        ul.addEventListener('click',function(event){
            // event.target  能获取你在页面点击的最底层的那个元素,例如页面点击的是li,则获取的是li,点击a,则获取的是a
        //    event.target.style.backgroundColor = 'black'

        // event.target.nodeName  可以获取节点的名称,获取的都是大写的 UL LI
        if(event.target.nodeName === 'LI'){
            event.target.style.backgroundColor = 'black'
        }
        })
    </script>
</body>

案例-用数组渲染学生信息

新知识
// <a data-index="2" href="javascript:" class="del">删除</a>

          // 获取到a标签 上存放的 index
          // event.target =  a标签的dom元素
          //8. console.dir(event.target.dataset.index)
          const index = event.target.dataset.index;
          //9.点击删除时,直接让a所在的对象直接删除掉
          arr.splice(index,1)
<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 button = document.querySelector('button')
        
       
        //姓名
        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')

        const tbody = document.querySelector('tbody')
       

        //1.生成数组,储存用户输入的数据
        let arr = []
        

         //2.封装函数,用数组渲染页面,生成tr
         function getMessage() {
           let tr = ``
           for (let index = 0; index < arr.length; index++) {
              
            tr += `<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 date-index = ${index} href="javascript:" class="del">删除</a>
          </td>
        </tr>`
           }

           tbody.innerHTML = tr 
           
         }
        
         //3.绑定发布点击事件
         button.addEventListener('click',function(){
           //4.把对象放入数据
           let obj = {
            id:Date.now(),
            uname:uname.value,
            age:age.value,
            gender:gender.value,
            salary:salary.value,
            city:city.value
           }
           arr.push(obj)
           //5.生成tr
          getMessage()
          //6.发布后清空内容
          uname.value = ''
          age.value = ''
          gender.value = '男'
          salary.value = ''
          city.value = '北京'

         })

         //7. 点击删除
         tbody.addEventListener('click',function(event){
          if (event.target.nodeName === 'A') {
          // <a data-index="2" href="javascript:" class="del">删除</a>

          // 获取到a标签 上存放的 index
          // event.target =  a标签的dom元素
          //8. console.dir(event.target.dataset.index)
          const index = event.target.dataset.index;
          //9.点击删除时,直接让a所在的对象直接删除掉
          arr.splice(index,1)
          //10.因为删除有对象,所以数组发生变化,所以要再次生成tr

          getMessage()
          }
         })
    </script>
  </body>
</html>

滚动事件

div.addEventListener('scroll',function(){
            console.log('快滚把');
        })
获取滚动的位置
 window.addEventListener('scroll',function(){
            console.log(document.documentElement.scrollTop);
           
        })
主动设置滚动的位置
button.addEventListener('click',function(){
            document.documentElement.scrollTop = 300
        })

案例-滚动固定标签

拓展知识-粘性定位

 .nav{
            height: 70px;
            background-color: rgb(69, 197, 58);
            /* 粘性定位,但是要考虑兼容性的问题 */
            position: sticky;
            left: 0;
            top: 0;
            width: 100%;
        }
<style>
        .header{
            height: 250px;
            background-color: rgb(228, 91, 91);
           
           
        }
        .nav{
            height: 70px;
            background-color: rgb(69, 197, 58);
        }
        .body{
            height: 600vh;
            background-color: rgb(49, 138, 207);
        }
        .fix{
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
        }
    </style>
</head>
<body>
    <div class="header"></div>
    <div class="nav"></div>
    <div class="body">
        <h3>1</h3>
      //此处省略99个h3标签
      
    </div>
    <script>
        const header = document.querySelector('.header')
        const nav = document.querySelector('.nav')
        window.addEventListener('scroll',function(){
            let height = document.documentElement.scrollTop
            if(height >= 250){
                nav.classList.add('fix')
                 /* 因为nav固定后会脱标,所以添加外边距跟nav的高度一样高 */
                header.style.marginBottom = '70px'
            }else{
                nav.classList.remove('fix')
                header.style.marginBottom = 0
            }
        })
    </script>
</body>
</html>

案例-点击火箭返回顶部

<style>
        body{
          
            height: 600vh;
            background-image: linear-gradient(red, blue);
        }
       
        p{
            display: none;
            position: fixed;
            right: 10px;
            bottom: 20px;
            width: 150px;
            height: 195px;
            background-image: url(../练习/火箭到顶部/images/gotop.png);
        }
        p:hover{
            background-image: url(../练习/火箭到顶部/images/gotop.gif);
            
        }

    </style>
</head>
<body>
        <p></p>
    <script>
        //1.滑动到一定的位置会出现火箭
        //2.鼠标移动到火箭上面会变成动图
        //3.点击火箭到达顶部
        const div = document.querySelector('div')
        const p = document.querySelector('p')
        window.addEventListener('scroll',function(){
            let num = document.documentElement.scrollTop
            if( num >= 500){
                p.style.display = 'block'
            }else{
                p.style.display = 'none'
            }
        })
        
        p.addEventListener('click',function(){
          
           let   setIn =  setInterval(function(){
              document.documentElement.scrollTop -= 50

              if(document.documentElement.scrollTop === 0){
               clearInterval(setIn)
           }

              
            },100)
        
           
        })
        
        
    </script>
</body>
</html>

第六节

拓展-自定义属性

相当于给一个东西添加标记

<body>
    <h1 data-num="123">我是标题</h1>
    <script>
        const h1 = document.querySelector('h1')
        h1.addEventListener('click',function(event){
            
            console.log(event.target.dataset.num); //123
        })
    </script>
</body>

加载事件

给 window 添加 load 事件:需要页面所有的元素都加载完才能执行(例如视频还没有加载完的话,都不算加载完)

<body>
    <h1>
        <img src="./火箭到顶部/images/gotop.png" alt="">
    </h1>
    <script>
        //需要等到页面所有的东西都加载完毕才会执行
        window.addEventListener('load',function(){
            const img = document.querySelector('img')
            const h1 = document.querySelector('h1')
            console.log(img.height); // 195
            h1.innerText = img.height //195
        })
      //只需要把标签加载完毕,就可以执行,无论图片有没有加载完毕,会比load事件更早触发
      document.addEventListener('DOMContentLoaded',function(){
        const img = document.querySelector('img')
            const h1 = document.querySelector('h1')
            console.log(img.height);   //报错,因为此时图片并没有加载完毕,所以无法获取图片的高度
            h1.innerText = img.height // 0
      })
    </script>
</body>

scroll家族

移动端的滚动条不占宽度!!!pc端默认占17px的宽度

scrollWidth:等于整个可以滚动的区间的宽度 不包含滚动条的大小

scrollHeight:整个可以滚动的区域的高度 不包含滚动条的大小

<style>
        .box{
            width: 300px;
            height: 300px;
            background-color: rgb(221, 145, 145);
            overflow: scroll;
        }
    </style>
</head>
<body>
    <div class="box">
           <h1>1</h1>
           //此处省略62个h1
    </div>
    <script>
       const div = document.querySelector('.box')
       
       //元素绑定滚动事件
       div.addEventListener('scroll',function(){
        console.log(this.scrollWidth); //等于整个可以滚动的区间的宽度 不包含滚动条的大小
        // 283 ,因为div加了滚动条,pc端的滚动条默认占17px (如果在水平方向也有滚动条,那宽度就等于在水平方向可滚动的距离,能滚动多少就是多少)  
        console.log(this.scrollHeight); //scrollHeight 整个可以滚动的区域的高度  不包含滚动条的大小
        //到可滚动最低的高度是:3804  是div可滚动距离的高度,而不是div的设置自身的高度 
       
       
       
        //获取当前div滚动的距离
        console.log(this.scrollTop); // 针对垂直方向的滚动
        console.log(this.scrollLeft); //针对水平方向的滚动
    
    })

     //页面绑定滚动事件
     window.addEventListener('scroll',function(){
         //获取页面滚动的距离
         document.documentElement.scrollTop
     })
     //移动端的滚动条不占宽度!!!pc端默认占17px的宽度
    </script>
</body>

offset家族

<style>
        .box{
            width: 300px;
            height: 300px;
            background-color: rgb(101, 127, 210);
            overflow: scroll;
            margin-top: 50px;
            margin-left: 100px;
        }
        .one{
           position: fixed;
           left: 500px;
           top: 100px;
            width: 300px;
            height: 300px;
            background-color: rgb(55, 195, 115);
           
        }
        .two{
          
            width: 100px;
            height: 100px;
            background-color: rgb(245, 38, 224);
           
        }
        .son{
          
            width: 50px;
            height: 50px;
            background-color: rgb(212, 48, 75);
            margin-top: 20px;
            margin-left: 20px;
        }
    </style>
</head>
<body>
    <div class="box">
        <h1>1</h1>
        //此处省略59个h1
    </div>
    <div class="one">
        <div class="two">
            <div class="son"></div>
        </div>
    </div>
    <script>
       const div = document.querySelector('.box')
       const two = document.querySelector('.two')
       const son = document.querySelector('.son')
       //获取元素的宽高
    //    console.log(div.offsetWidht); //300(包含滚动条的大小)
    //    console.log(div.offsetHeight); //300(包含滚动条的大小)
      
        console.log(div.offsetWidth); // 300 获取的是元素自身设置的宽 css设置时多少那就是多少
        console.log(div.offsetHeight) // 300 获取的是元素自身设置的高  css设置时多少那就是多少
        console.log(div.offsetTop) // 50  此时没有定位的父级,所以相对页面
        console.log(div.offsetLeft) // 108 (8px是页面自带的边距) 此时没有定位的父级,所以相对页面
   
        console.log(two.offsetTop) // 0 此时有定位的父级,此时的位置就相对父级而言
        console.log(two.offsetLeft) // 0 此时有定位的父级,此时的位置就相对父级而言


        console.log(son.offsetTop) // 20 父级也可以是祖父或以上
        console.log(son.offsetLeft) // 20  父级也可以是祖父或以上
       //offsetTop:获取的是元素相对定位父级的上面距离,如果没有定位的父级,那就是相对于页面
       //offsetLeft:获取的是元素相对定位父级的左边距离,如果没有定位的父级,那就是相对于页面
    </script>
</body>

client家族

<style>
        .box{
            width: 300px;
            height: 300px;
            background-color: rgb(101, 127, 210);
            overflow: scroll;
            margin-top: 50px;
            margin-left: 100px;
            border: 2px solid pink;
        }
    
    </style>
</head>
<body>
    <div class="box">
        <h1>1</h1>
        //此处省略59个h1
    </div>
  
    <script>
       const div = document.querySelector('.box')
         console.log(div.clientWidth); //283 获取的是元素自身在css设置的宽度,但是不包含滚动条的
         console.log(div.clientHeight); // 283 获取的是元素自身在css设置的高度,但是不包含滚动条的
         console.log(div.clientTop);  // 2 获取的是元素在css设置的上边框的宽度
         console.log(div.clientLeft);// 2 获取的是元素在css设置的左边框的宽度
    </script>
</body>

三个家族对比总结

1649908038813.png

resize屏幕大小改变事件

 <script>
        window.addEventListener('resize',function(){
     document.documentElement.style.fontSize =
            document.body.offsetWidth / 10 + 'px';
            let width = document.documentElement.offsetWidth

            if(width > 1080){
                document.documentElement.querySelector('title').innerText='大屏幕'
            }else if(width > 850){
                document.documentElement.querySelector('title').innerText='中等屏幕'
            }else if(width > 650){
                document.documentElement.querySelector('title').innerText='小屏幕'
            }else {
                document.documentElement.querySelector('title').innerText='极小屏幕'
            }
        })
    </script>

案例-焦点轮播图-利用精准定位达到排他效果

<script>
      //1.点击下面的小图片,上面的图片跟文字跟随变化
      //2.排他,点击那个那个变量,对应得大图片显出来,下边框也是

      const li = document.querySelectorAll('.slides li') // 获取大图
      const small = document.querySelectorAll('.indicator li') //获取小图
     
      const h3 = document.querySelector('h3')
       for (let index = 0; index < small.length; index++) {
        small[index].addEventListener('click',function(){
            document.querySelector('.slides li.active').classList.remove('active')
             document.querySelector('.indicator li.active').classList.remove('active')
             
             this.classList.add('active')
             li[index].classList.add('active')

          h3.innerText = `第${index + 1}张图的描述信息`

        })
         
       }
    </script>

swiper插件的运用

1.网站:www.swiper.com.cn/usage/index…

1649923238679.png 2. -下载--

1649923291839.png 3.搜索一些功能-点击API文档-进入里面搜索

1649923407859.png 5.

1649923424615.png

window对象

1.BOM对象

1649923681135.png

2.设置延时器

 <script>
        let time = setTimeout(function(){
            console.log('我是延时器');
        },4000)

        //清除延时器
        clearTimeout(time)
    </script>

3.案例-使用延时器实现定时器的功能-递归

 <script>
     //自己调用自己就是递归
        let num = 0
        function fuc(){
            num++

            setTimeout(fuc,100)
            console.log(num);
        }
        fuc()
    </script>

4.Location对象

作用:跳转功能 / 刷新功能/获取网站地址栏?号后面的值/获取网站#号后面的值

<body>
    <button>点击我跳转</button>
   
    <script>
           const button = document.querySelector('button')
           button.addEventListener('click',function(){
               //跳转功能
               location.href = 'https://www.swiper.com.cn/';

            //刷新功能
            location.href = location.href

            //强制刷新
            location.reload(true)

            //获取网站地址栏问号后面的东西 ?123(自己随便写的)
            console.log(location.search);
            //获取网站地址栏#号后面的东西  #123
            console.log(location.hash); 
           })

           //5秒后就算不点击也会自动跳转
           setTimeout(function(){
            location.href = 'https://www.swiper.com.cn/';
           },5000)

    </script>
</body>

5.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'
            }
        })()

6.history对象

<body>
    <a href="https://www.swiper.com.cn/">点击我跳转</a>
    <a href="https://www.w3cschool.cn/css3/">点击我跳转</a>
    <button class="box1">去下个页面</button>
    <button class="box2">返回之前页面</button>
    <script>
    const  box1=document.querySelector('.box1')
    const  box2=document.querySelector('.box2')
    box1.addEventListener('click',function(){
        history.forward()
        // history.go(1)  作用同上
    })
    box2.addEventListener('click',function(){
       history.back()
    //    history.go(-1) 作用同上
    })
    </script>
</body>

第七节

拓展知识,区分方法和属性

1649985022625.png

1.本地储存

sessionStorage和localStorage约 5M 左右
localStorage:生命周期永久生效,除非手动删除 否则关闭页面也会存在
sessionStorage:生命周期为关闭浏览器窗口 用法和localStorage一样
<body>
    <input type="color" >
    <script>
    const input = document.querySelector('input')
 
    input.addEventListener('change',function(){
        //储存数据 字符串类型
        localStorage.setItem('bgc',input.value)
        document.body.style.backgroundColor = input.value
    })
                                            //获取数据
    document.body.style.backgroundColor = localStorage.getItem('bgc')
    //删除数据
    localStorage.removeItem('bgc')


    //储存复杂类型的数据

    const obj = {
        name:'悟空',
        age : 18

    }

    //把对象转换成字符串
    const arrStr = JSON.stringify(obj)
    localStorage.setItem('obj',arrStr)
    //获取数据,把数据类型转回数组
    const arrGet=  JSON.parse(localStorage.getItem('obj'))
    console.log(arrGet);
    localStorage.removeItem('obj')  //删除一个
    localStorage.clear() //删除全部
    </script>
</body>

2.自定义属性

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

<body>
    <a href="https://gitee.com/" data-index="666" aa="456">你好</a>
    <script>
         const a = document.querySelector('a')
         //获取固有属性 href
         console.log(a.href);
         //获取标准的自定义属性
         console.log(a.dataset.index)
         //获取自己瞎写的 这个最厉害,无论是自己瞎写的还是固有属性都能获取
         
         console.log(a.getAttribute('aa'))

         //在js里面设置自定义属性
            a.setAttribute('bb','你好')
            console.log(a.getAttribute('bb'))

            //清除属性
            a.removeAttribute('aa')
    </script>
</body>

1649995592813.png

3.高阶函数

1649996627557.png

4.重绘和回流

回流(重排)

​ 当 Render Tree 中部分或者全部元素的尺寸、结构、布局等发生改变时,浏览器就会重新渲染部分或全部文档的过程称为 回流。

重绘

​ 由于节点(元素)的样式的改变并不影响它在文档流中的位置和文档布局时(比如:color、background-color、outline等), 称为重绘。

重绘不一定引起回流,而回流一定会引起重绘。
会导致回流(重排)的操作:

页面的首次刷新 浏览器的窗口大小发生改变 元素的大小或位置发生改变 改变字体的大小 内容的变化(如:input框的输入,图片的大小) 激活css伪类 (如::hover) 脚本操作DOM(添加或者删除可见的DOM元素) 简单理解影响到布局了,就会有回流

5.取消事件绑定

<body>
    <button>点击我,输出爱你哦</button>
    <script>
   const button = document.querySelector('button')
   function sayLove() {
       console.log('爱你爱你');
   }
   //绑定点击事件,此时的函数必须是具名函数
   button.addEventListener('click',sayLove)
   //取消事件绑定 如果绑定事件时用的是匿名函数,将无法取消
   setTimeout(function(){
    button.removeEventListener('click',sayLove)
   },8000)
    </script>
</body>

6.字符串方法

 <script>
        //转大写
        let num = 'abcd'
      console.log(num.toUpperCase());  
      //转小写
      let num2 = 'ABCD'
      console.log(num2.toLowerCase()); 
       //字符串转数组
       let num3 = 'abcdhyk'
       console.log(num3.split('')); 
       let num4 = 'a-b-c-d-h-y-k'
       console.log(num4.split('-')); 

    </script>

7.数组方法

 <script>
        //数组转字符串
        const arr = ['a','b','c','d','e']
        console.log(arr.join('-')); //'a-b-c-d-e'

        //数组之间合并 字符串合并用这个方法同样可以实现,但是字符串直接用 + 号就可以实现合并
        const arr2 = [1,2,3,4,5]
        const arr3 = ['一','二','三','四']
        console.log(arr2.concat(arr3));//[1, 2, 3, 4, 5, '一', '二', '三', '四']
    </script>

8.正则表达式

正则表达式(Regular Expression)是用于匹配字符串中字符组合的模式

作用:

表单验证(匹配) 过滤敏感词(替换) 字符串中提取我们想要的部分(提取)

 <script>
        //1.声明一个变量 来放要检测的内容
        let verify = /帅气/;
        const arr = '他是一个傻逼自信又无辜又敏感又开朗又帅气的人'
        //如果有。输出是treu 没有是false
        console.log(verify.test(arr)); //true
    </script>

8.1元字符

1.边界符
<script>
        //^表示匹配首个字  $匹配最后一个字
      
        const arr = '他是一个傻逼自信又无辜又敏感又开朗又帅气的人'
        let verify = /^帅气/;
        let verify2 = /^他是/;
        let verify3 = /^帅气$/;
        let verify4 = /^他人$/;
        let verify5 = /帅气的人$/;
        //如果有。输出是treu 没有是false
        console.log(verify.test(arr)); //false
        console.log(verify2.test(arr)); //true
        console.log(verify3.test(arr)); //false
        console.log(verify4.test(arr)); //false
        console.log(verify5.test(arr)); //true
    </script>
2.量词
 <script>
        //在*号前面的字符,出现0或更多次
        // console.log(/^吃*$/.test('')); true
        // console.log(/^吃*$/.test('吃'));true
        // console.log(/^吃*$/.test('吃吃'));true
        // console.log(/^吃*$/.test('吃吃吃'));true

        //在?号前面的字符,出现0或一次
        // console.log(/^吃?$/.test('')); //true
        // console.log(/^吃?$/.test('吃'));//true
        // console.log(/^吃?$/.test('吃吃'));//false
        // console.log(/^吃?$/.test('吃吃吃'));//false

        //{n} 重复n次
        console.log(/^吃{2}$/.test('')); //false
        console.log(/^吃{2}$/.test('吃'));//false
        console.log(/^吃{2}$/.test('吃吃'));//true
        console.log(/^吃{2}$/.test('吃吃吃'));//false
    </script>

1650013996209.png

3.字符类
 //  . 表示除了(换行符)之外的全部字符
        console.log(/./.test('飞')); //true
        console.log(/路.飞/.test('路大飞')); //true


// [] 表示一个范围,a-zA-Z 0-9 1-9
        console.log(/[a-gA-Z]/.test('J'));//true
        console.log(/[a-g]/.test('z'));//false

//\w 只有有字母,数字,下划线,就符合

        console.log(/\w/.test('路9'));//true
        console.log(/\w/.test('%%'));//false

        //\W 除了字母,数字,下划线,就符合

        console.log(/\W/.test('%%'));//true
        console.log(/\W/.test('9'));//false

//验证手机号码 第一个数字必须是1 第二个数字:35789 其他9位数字
        console.log(/^1[35789]\d{9}$/.test('12563248841'))//false
        console.log(/^1[35789]\d{9}$/.test('13535412167'))//true



1650016444499.png