Web APIs -第3章笔记

  • 事件流
  • 移除事件监听
  • 其他事件
  • 元素尺寸与位置
  • 综合案例

事件流

为什么要学习事件流?

  • 可以帮我们解决一些疑惑,比如点击子盒子会会弹出2次的问题

<script>
  // 事件流
  const father =document.querySelector('.father')
  const son =document.querySelector('.son')
  // 点击父盒子
  father.addEventListener('click',function (){
    alert(我是爸爸)
  }
  // 点击子盒子
  son.addEventListener('click',function (){
    alert(‘我是儿子)
  }
  </script>

什么是事件流:事件流指的是事件完整执行过程中的流动路径

当触发事件时,会经历两个阶段,分别是捕获阶段冒泡阶段

事件捕获概念:

当一个元素的事件被触发时,会从DOM的根元素开始依次调用同名事件 (从外到里)

捕获

事件捕获需要写对应代码才能看到效果

语法:

 元素.addEventListener('click', 回调函数, 是否使用捕获机制true/false)  
<body>
  <div class="father">
    父盒子
    <div class="son">子盒子</div>

  </div>

  <script>
    // 事件流
    const father = document.querySelector('.father')
    const son = document.querySelector('.son')
    // 1. 事件捕获
    // // 点击父盒子
     father.addEventListener('click', function () {
       alert('我是爸爸')
     }, true)  // 开启事件捕获
     // 点击子盒子
     son.addEventListener('click', function () {
       alert('我是儿子')
     }, true) // 开启事件捕获
  </script>

</body>

说明:

  • addEventListener第三个参数传入 true 代表是捕获阶段触发(很少使用)
  • 若传入false代表冒泡阶段触发,默认就是 false

事件冒泡

事件冒泡概念:

当一个元素的事件触发时,同样的事件将会在该元素的所有祖先元素中依次被触发。这一过程被称为事件冒泡

  • 简单理解:当一个元素触发事件后,会依次向上调用所有父级元素的 同名事件
  • 事件冒泡是默认存在的,或者第三个参数传入 false 都是冒泡
  • 实际工作都是使用事件冒泡为主
<body>
  <div class="father">
    父盒子
    <div class="son">子盒子</div>

  </div>

  <script>
    // 事件流
    const father = document.querySelector('.father')
    const son = document.querySelector('.son')
    // 2. 事件冒泡
    // 点击父盒子
    father.addEventListener('click', function () {
      alert('我是爸爸')
    })
    // 点击子盒子
    son.addEventListener('click', function () {
      alert('我是儿子')
    }, false) 
  </script>

</body>

阻止冒泡

问题:因为默认有冒泡阶段的存在,所以容易导致事件影响到父级元素(祖先元素)

需求:若想把事件限制在当前元素内,就需要阻止事件冒泡

前提:阻止事件冒泡需要拿到事件对象

语法:

<body>
  <div class="father">
    父盒子
    <div class="son">子盒子</div>

  </div>

  <script>
    // 事件流
    const father = document.querySelector('.father')
    const son = document.querySelector('.son')
    // 1. 事件冒泡
    // 点击父盒子
    father.addEventListener('click', function () {
      alert('我是爸爸')
    })
    // 点击子盒子
    son.addEventListener('click', function (e) {
      alert('我是儿子')
      // 1.1 先获取事件对象
      // 1.2 事件对象.stopPropagation()  注意是个方法 
      e.stopPropagation()
    }) 
  </script>

</body>

结论:事件对象中的 stopPropagation 方法,专门用来阻止事件冒泡(事件传播)

注意:stopPropagation 方法可以阻断事件流动传播,不光在冒泡阶段有效,捕获阶段也有效

鼠标经过事件:

mouseover 和 mouseout 会有冒泡效果

mouseenter 和 mouseleave 没有冒泡效果 (推荐)

事件委托

事件委托(EventDelegation):是JavaScript中注册事件的常用技巧,也称为事件委派、事件代理

简单理解:原本需要注册在子元素的事件委托给父元素,让父元素担当事件监听的职务

为什么要用事件委托呢?

  • 如果同时给多个元素注册事件,还需要利用循环多次注册事件
  • 大量的事件监听是比较耗费性能的,如下代码所示

<script>
  // 假设页面中有 10000 个 button 元素
  const lis = document.querySelectorAll('ul li');

  for(let i = 0; i <= lis.length; i++) {
    // 为 10000 个 button 元素添加了事件
    lis[i].addEventListener('click', function () {
      // 省略具体执行逻辑...
    })
  }
</script>

上述问题,可以使用事件委托来优化

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

  • 优点:减少注册次数,可以提高程序性能
  • 原理:事件委托其实是利用事件冒泡的特点
    • 父元素注册事件,当我们触发子元素的时候,会冒泡到父元素身上,从而触发父元素的事件

得到子元素

利用事件委托方式如何得到当前点击的元素呢?

  • 实现:
    • 事件对象.target获得触发事件的元素对象
    • 事件对象.target. tagName 可以获得真正触发事件的元素名
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        ul{
            background-color:green;
        }
    </style>
</head>
<body>
    <ul>
        <li>第1个孩子</li>
    
        <li>第2个孩子</li>
    
        <li>第3个孩子</li>
    
        <li>第4个孩子</li>
    
        <li>第5个孩子</li>
    
      </ul>
      <script>
        // 需求: 点击每个小li都会有弹窗效果
        // 1. 获取父元素ul
        const ul = document.querySelector('ul')
    
        // 2. 给ul注册点击事件
        ul.addEventListener('click', function (e) {
          // alert('我会弹窗')
          // 3. 利用事件对象.target 得到目标元素
          console.log(e.target)
        //   e.target.style.background = 'pink'
    
          // 需求2:点击哪个小li,对应的li变色
          // console.dir(e.target.tagName) 可以得到目标元素的标签名
          if (e.target.tagName === 'LI') {
            e.target.style.color = 'white'
          }
        })
      </script>
</body>
</html>

阻止默认行为

什么是默认行为?浏览器对某些html元素时存在一些默认行为的

  • 像用户点击了a标签,浏览器默认会发生一次跳转
  • 用户点击了表单中的提交按钮时浏览器会自动提交一次表单
<a href="http://ithome.com">IT Home</a>

<form>
  <input type="text">
  <input type="password">
  <botton>登录</botton>
</form>

阻止元素发生默认的行为:在给html元素注册事件后,可以在事件函数中阻止它们的默认行为,从而让我们的功能变得正常

  • 阻止链接的跳转等等
  • 当点击提交按钮时阻止对表单的提交

语法:

事件对象.preventDefault()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="">
      姓名: <input type="text" class="username">
      <button>提交</button>
  
    </form>
  
    <a href="http://www.baidu.com">点击跳转</a>
  
    <script>
      // 阻止默认行为
      const form = document.querySelector('form')
      const input = document.querySelector('.username')
      form.addEventListener('submit', function (e) {   
          e.preventDefault()  // 阻止提交事件  
          console.log(input.value)
      })
  
      document.querySelector('a').addEventListener('click', function (e) {            
        e.preventDefault()
        console.log(e.target.innerHTML)
      })
    </script>
  
  </body>
  
</html>

事件解绑

移除事件处理函数,也称为解绑事件

<body>
  <button class="l2">移除L2事件监听</button>

  <button class="l0">移除L0事件监听</button>

  <script>
    // 需求:按钮就点击一次,然后移除点击事件

    // 1. l2事件监听
    const l2 = document.querySelector('.l2')

    l2.addEventListener('click', fn)
    function fn() {
      alert('我点击了')
      // 移除事件监听
      l2.removeEventListener('click', fn)
    }

    // 2. l0事件监听
    const l0 = document.querySelector('.l0')
    l0.onclick = function () {
      alert('我点击了')
      // 移除事件监听
      l0.onclick = null
    }
  </script>

</body>

两种注册事件的区别:

on注册(L0)

  1. 同一个对象,后面注册的事件会覆盖前面注册(同名事件)
  2. 直接使用null覆盖就可以实现事件的解绑
  3. 只有冒泡阶段,没有捕获阶段

事件监听注册(L2)

  1. 语法: addEventListener(事件类型, 事件处理函数, 是否使用捕获)
  2. 后面注册的事件不会覆盖前面注册的事件(同名事件)
  3. 必须使用removeEventListener(事件类型, 事件处理函数, 获取捕获或者冒泡阶段)实现事件解绑
  4. 可以通过第三个参数去确定是在冒泡或者捕获阶段执行
  5. 匿名函数无法被解绑

其他事件

页面加载事件

页面加载事件,分为 loadDOMContentLoaded 两个,在页面加载完毕后触发,可以用来处理一些需要再页面加载完成后才能处理的一些逻辑

页面加载解决什么问题?

  • 老代码喜欢把 script 写在 head 中,这时候直接找 dom 元素找不到,可以使用页面加载时间来解决
事件名:load

加载外部资源(如图片、外联CSS和JavaScript等)加载完毕时触发的事件

load事件基本语法:

给window添加load事件

window.addEventListener('load', function() {
    // xxxxx
})

事件名:DOMContentLoaded

作用:当初始的 HTML 文档被完全加载和解析完成之后就触发,而无需等待样式表、图像等完全加载

基本语法:

给 document 添加 DOMContentLoaded 事件

document.addEventListener('DOMContentLoaded', function() {
    // xxxxx
})

load和DOMContentLoaded区别:

  1. load注册在window上,DOMContentLoaded注册在 document 上;
  2. load 事件要晚于 DOMContentLoaded 事件被执行;
  3. DOMContentLoaded事件是在文档(DOM)完全加载并解析完毕后立即触发,无需等待样式表、图片等外部资源加载完成;
  4. load事件要求文档(DOM)本身已经加载完毕,还要求所有关联的资源(包括但不限于图片、脚本文件、CSS文件等)也全部加载完成 ,才触发。

两个事件的场景选择:

  1. DOMContentLoaded 更适合于那些只需要文档结构而不需要额外资源就可运行的情况;
  2. load适用于需要确保整个页面包括其引用的所有资源都已加载完成的情况下。

元素滚动事件

事件名:scroll

滚动条在滚动的时候持续触发的事件,用来监听整个页面滚动 或者某个元素滚动

为什么要学?

  • 很多网页需要检测用户把页面滚动到某个区域后做一些处理,比如固定导航栏,比如返回顶部

基本语法:

  1. 监控浏览器中整个页面的滚动行为,可以将scroll事件绑定到 window上
  2. 监控某个html元素的滚动行为,将scroll实践绑定到该元素上

前置条件:内容高度或者宽度要超过元素本身的宽高,才会产生滚动条

// ✨✨推荐
window.addEventListener('scroll', function() {
    // xxxxx
  console.log(document.documentElement) // 得到网页根元素html
  console.log(document.documentElement.scrollTop) //浏览器垂直滚动时- 获取被卷去的头部距离
  console.log(document.documentElement.scrollLeft)//浏览器水平滚动时- 获取被卷去的左侧距离
})

DOM元素.addEventListener('scroll', function() {
    // xxxxx
  DOM元素.scrollTop   //元素垂直滚动时- 获取被卷去的头部距离
  DOM元素.scrollLeft //元素水平滚动时- 获取被卷去的左侧距离
})

scrollTop / scrollLeft, 被卷去的头部或者左侧,可以读取,也可以修改(赋值可以让页面滚动到指定位置)

随堂案例

需求:滚动scrollTop>=300则出现 top按钮,点击top按钮后带有动画滚动到顶部

技术分析:

  1. 在window上注册scroll事件,获取document.documentElement.scrollTop
  2. if判断 scrollTop的值>=300 显示top按钮,透明度(opacity的值 1表示不透明-即显示,0:透明-即隐藏)
  3. if判断scrollTop的值<300 隐藏top按钮
  4. 点击top按钮,修改document.documentElement.scrollTop = 0 (没有滚动动画)

需要配合html{ scroll-behavior: smooth; } 才有滚动动画

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            background-color: #384B85;
        }

        .top {
            width: 42px;
            height: 62px;
            background-image: url(./images/top.png);
            background-size: cover;
            position: fixed;
            right: 30px;
            bottom: 50px;
            opacity: 0;
            cursor: pointer;

            transition: all 0.5s;
        }

        .content {
            height: 3000px;
        }
 html{
            scroll-behavior: smooth;
        }
    
    </style>
</head>

<body>
    <div class="top"></div>
    <div class="content">
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
        <h1>我是顶部内容</h1>
    </div>

    <script>
        const topBox = document.querySelector('.top')
        const htmlBox = document.querySelector('html')

        topBox.addEventListener('click',function(){
            // 没有滚动动画,需要配合html{scroll-behavior: smooth;}才有动画
            document.documentElement.scrollTop = 0

            // 有滚动动画
            // document.documentElement.scrollTo({
            //     top:0,
            //     left: 0,
            //     behavior:"smooth"
            // })
        })

        window.addEventListener('scroll', function () {
            let top = document.documentElement.scrollTop
            console.log(top)
            
            if(top >= 300) {
                topBox.style.opacity = 1

            }else{
                topBox.style.opacity = 0
    
            }
        })
    </script>
</body>

</html>

页面尺寸事件

在窗口尺寸改变的时候触发事件resize

使用场景: 改变小米官网 Xiaomi SU7,Xiaomi 14 Ultra,小米澎湃OS,小米徕卡影像大赛 尺寸,内容布局会改变

基本语法:

window.addEventListener('resize', function() {
    // xxxxx
})

clientWidth和clientHeight,获取元素的可见部分宽高(不包含border,margin,滚动条等)

两种用法:

  1. 获取页面大小

document.documentElement.clientWidth

document.documentElement.clientHeight

  1. 获取元素大小

dom元素.clientWidth

dom元素.clientHeight

举例:页面中的div盒子当页面宽>=400时,背景为绿色green,<400时为黄色yellow

<!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>
  <style>
    .box {
      width: 200px;
      height: 200px;
      padding: 5px;
      border: 10px solid red;
      background-color: pink;
    }
  </style>
</head>

<body>
  <div class="box"></div>
  <script>
    // 1.页面尺寸事件
    const box = document.querySelector('.box')
    window.addEventListener('resize', function () {      
      if(document.documentElement.clientWidth >400){
        box.style.backgroundColor = 'green'
      }else{
        box.style.backgroundColor = 'yellow'
      }
      console.log('页面尺寸变了',document.documentElement.clientWidth)
    })

  </script>
</body>

</html>

元素尺寸与位置

获得元素自己的【尺寸大小】和元素在【页面中的位置】

大小:offsetWidth 和 offsetHeight

位置: offsetLeft 和 offsetTop

<!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>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .father {
      /* position: relative; */
      width: 300px;
      height: 300px;
      padding: 5px;
      border: 10px solid red;
      margin: 100px;
      background-color: pink;
    }

    .son {
      width: 100px;
      background-color: purple;
    }
  </style>
</head>

<body>
  <div class="father">
    <div class="son">
      里面包含一些文字
      里面包含一些文字
      里面包含一些文字
    </div>
  </div>
  <script>
    // offsetWidth和offsetHeight

    // offsetLeft和offsetTop

  </script>
</body>

</html>

随堂练习

使用元素位置实现b站的导航栏,下横线效果

使用 offsetLeft 获取到所有a标签的位置,结合 transform样式属性实现

 lineBox.style.transform = `translateX(${e.target.offsetLeft}px)`

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .tabs {
            position: relative;
            width: 600px;
            height:50px ;
            margin: 50px auto;
            /* background-color: pink; */
        }

        .list a {        
            font-size: 22px;
            color: #333;
            text-decoration: none;
            padding: 10px;
        }

        .line{
            position: absolute;
            left:12px;
            top:40px;
            width: 40px;
            height: 3px;
            background-color: #fb7299;
            transition: all 0.2s;
          
        }
    </style>
</head>

<body>
    <div class="tabs">
        <!-- 很宽的盒子 -->
        <div class="list">

            <a href="#">首页</a>
            <a href="#">动画</a>
            <a href="#">番剧</a>
            <a href="#">果蔬</a>
            <a href="#">音乐</a>
            <a href="#">舞蹈</a>
            <a href="#">鬼畜</a>
            <a href="#">吹鬼</a>
        </div>

        <!-- 红色线 -->
        <div class="line"></div>
    </div>   
</body>

</html>
 <script>
        const listBox = document.querySelector('.list')
        const lineBox = document.querySelector('.line')

        listBox.addEventListener('click',function(e){
          if(e.target.tagName === 'A'){
            console.log(  e.target.offsetLeft)
            lineBox.style.transform = `translateX(${e.target.offsetLeft}px)`
          }          
        })
    </script>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值