• js-webApi 笔记2之DOM事件


    目录

    1、表单事件

     2、键盘事件

    3、事件对象

    4、排他思想

    5、事件流 

     6、捕获和冒泡

     7、阻止默认和冒泡

    8、事件委托

    9、事件解绑

    10、窗口加载事件

    11、窗口尺寸事件

    12、元素尺寸和位置

    13、窗口滚动事件

    14、日期对象

     15、节点

    16、鼠标移入事件


    1、表单事件

    获取焦点   onfoucus
    失去焦点    onblur

    1. <input type="text" />
    2. <script>
    3. // onfocus onblur
    4. const ipt = document.querySelector('input')
    5. // 获取焦点
    6. ipt.addEventListener('focus', function () {
    7. console.log('获得焦点了!!!')
    8. })
    9. // 失去焦点
    10. ipt.addEventListener('blur', function () {
    11. console.log('失去焦点了!!!')
    12. })
    13. // js方法 focus() blur()
    14. ipt.focus()
    15. script>

     2、键盘事件

    input事件      输入内容就触发   实时获取文本框内容
    keyup       键盘抬起

    keydown   键盘按下   获取的是上一次的内容

        事件执行顺序    keydown ---->input ----->keyup
        
        获取用户输入的完整内容  keyup 或 input

    1. <textarea rows="10" cols="30" placeholder="请输入评论"> textarea>
    2. <script>
    3. const tarea = document.querySelector('textarea')
    4. // input事件 输入内容就触发
    5. tarea.addEventListener('input', function () {
    6. console.log('正在输入')
    7. console.log(tarea.value)
    8. })
    9. tarea.addEventListener('keyup', function () {
    10. console.log('keyup')
    11. console.log(tarea.value)
    12. }),
    13. tarea.addEventListener('keydown', function () {
    14. console.log('keydown')
    15. console.log(tarea.value)
    16. })
    17. // 顺序 keydown -> input -> keyup
    18. // 获取用户输入的完整内容 keyup 或input
    19. script>

    3、事件对象

    事件对象:当事件发生后,浏览器会把当前事件相关的信息会封装成一个对象
    获取: 事件处理程序的第一个形参
     常用事件对象属性     e.target---->事件源     e.key---->按键字符串

       e.key    判断按的是什么键
     

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8" />
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    7. <title>Documenttitle>
    8. head>
    9. <body>
    10. <div class="box">1223div>
    11. <textarea rows="10" cols="30" placeholder="请输入评论"> textarea>
    12. <script>
    13. const tarea = document.querySelector('textarea')
    14. const box = document.querySelector('.box')
    15. /*
    16. 事件对象:当事件发生后,浏览器会把当前事件相关的信息会封装成一个对象
    17. 获取: 事件处理程序的第一个形参
    18. 常用事件对象属性 e.target -> 事件源 e.key -> 按键字符串
    19. */
    20. box.addEventListener('click', function (e) {
    21. console.log(e.target) // box
    22. })
    23. // input事件 输入内容就触发
    24. tarea.addEventListener('input', function () {
    25. console.log('正在输入')
    26. console.log(tarea.value)
    27. })
    28. tarea.addEventListener('keyup', function () {
    29. console.log('keyup')
    30. console.log(tarea.value)
    31. }),
    32. tarea.addEventListener('keydown', function (e) {
    33. console.log('keydown')
    34. console.log(e.key)
    35. if (e.key === 'Enter') {
    36. console.log('你按的是enter')
    37. }
    38. })
    39. // 顺序 keydown -> input -> keyup
    40. // 获取用户输入的完整内容 keyup 或input
    41. script>
    42. body>
    43. html>

    4、排他思想

    排他思想就是清除其他人的样式,只给自己设置

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8" />
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    7. <title>Documenttitle>
    8. <style>
    9. .box {
    10. display: flex;
    11. }
    12. .box div {
    13. width: 100px;
    14. height: 40px;
    15. background-color: skyblue;
    16. margin: 20px;
    17. text-align: center;
    18. line-height: 40px;
    19. }
    20. style>
    21. head>
    22. <body>
    23. <div class="box">
    24. <div>div1div>
    25. <div>div2div>
    26. <div>div3div>
    27. <div>div4div>
    28. div>
    29. <script>
    30. // 需求 点击某个div div背景色变成红色
    31. // 1 获取所有div
    32. const divs = document.querySelectorAll('.box > div')
    33. // 2 循环绑定事件
    34. for (let i = 0; i < divs.length; i++) {
    35. divs[i].addEventListener('click', function () {
    36. //把其余的div背景色去掉 对当前点击的div设置
    37. // 先干掉所有人-> 让所有的div背景色清空
    38. for (let j = 0; j < divs.length; j++) {
    39. divs[j].style.backgroundColor = ''
    40. }
    41. // 再对自己设置
    42. // divs[i].style.backgroundColor = '#f00'
    43. this.style.backgroundColor = '#f00'
    44. })
    45. }
    46. script>
    47. body>
    48. html>

    5、事件流 

    事件流->事件完整执行过程中的流动路径

    捕获阶段->目标阶段->冒泡阶段

    window->document->html->body->div->body->html->document->window

      捕获阶段:document-- >html-->body-->div-->span

     目标阶段: sapn

     冒泡阶段: span-- > div-- > body-- > html-- > document

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>Documenttitle>
    7. head>
    8. <body>
    9. <div class="box">div>
    10. <div class="son">sondiv>
    11. <script>
    12. const box=document.querySelector('.box')
    13. const son=document.querySelector('.son')
    14. //捕获阶段 true
    15. window.addEventListener('click',function() {
    16. console.log('window')
    17. },true)
    18. document.addEventListener('click',function() {
    19. console.log('document')
    20. },true)
    21. document.documentElement.addEventListener('click',function() {
    22. console.log('html')
    23. },true)
    24. document.body.addEventListener('click',function() {
    25. console.log('body')
    26. },true)
    27. box.addEventListener('click',function() {
    28. console.log('box')
    29. },true)
    30. son.addEventListener('click',function() {
    31. console.log('son')
    32. })
    33. son.addEventListener('click',function() {
    34. console.log('son')
    35. },true)
    36. // 冒泡 false 默认冒泡
    37. window.addEventListener('click',function() {
    38. console.log('window')
    39. })
    40. document.addEventListener('click',function() {
    41. console.log('document')
    42. })
    43. document.documentElement.addEventListener('click',function() {
    44. console.log('html')
    45. })
    46. document.body.addEventListener('click',function() {
    47. console.log('body')
    48. })
    49. box.addEventListener('click',function() {
    50. console.log('box')
    51. })
    52. script>
    53. body>
    54. html>

     6、捕获和冒泡

    捕获和冒泡:

    js里不会同时出现捕获和冒泡阶段,只能出现一个

    传统事件 onclick只有冒泡阶段 传统事件中如果给一个元素添加多个相同的事件时会出现覆盖

    事件监听addEventListener(事件类型,事件处理程序,布尔值)

    事件监听可以给元素添加多个相同的事件,会自上而下按顺序执行

    如果布尔值为空或false时,是冒泡阶段 为true时是捕获阶段

     7、阻止默认和冒泡

    阻止默认和冒泡:

    e.preventDefault() 阻止默认行为

    e.stopPropagation() 阻止冒泡行为

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>Documenttitle>
    7. <style>
    8. .father {
    9. width: 500px;
    10. height: 400px;
    11. background-color: pink;
    12. }
    13. .son {
    14. width: 200px;
    15. height: 200px;
    16. background-color: yellowgreen;
    17. }
    18. style>
    19. head>
    20. <body>
    21. <div class="father">
    22. <div class="son">div>
    23. div>
    24. <a href="http://www.baidu.com">百度a>
    25. <script>
    26. var father = document.querySelector('.father')
    27. var son = document.querySelector('.son')
    28. var a = document.querySelector('a')
    29. // e.preventDefault() 阻止默认行为
    30. a.addEventListener('click', function (e) {
    31. e.preventDefault()
    32. })
    33. // e.stopPropagation() 阻止冒泡行为
    34. son.addEventListener('click', function (e) {
    35. // alert('我是1')
    36. alert('我是儿子')
    37. e.stopPropagation()
    38. })
    39. father.addEventListener('click', function () {
    40. alert('我是爸爸')
    41. }, false)
    42. script>
    43. body>
    44. html>

    8、事件委托

    事件委托:给父元素添加事件来处理子元素,原理是使用冒泡 ,点击谁谁的背景颜色发生改变

    e.target

    ul li 中 给li设置背景颜色,给ul设置事件来设置li,提高了代码程序的性能

    鼠标位置:clientX/Y    相对于可视窗口的X,Y轴的坐标

    pageX/Y     是相对于页面的坐标

    screenX/Y   相对于屏幕的位置

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>Documenttitle>
    7. head>
    8. <body>
    9. <ul>
    10. <li>iiili>
    11. <li>bbbli>
    12. <li>cccli>
    13. <li>sssli>
    14. ul>
    15. <script>
    16. const ul=document.querySelector('ul')
    17. ul.addEventListener('click',function(e) {
    18. e.target.style.backgroundColor='pink'
    19. })
    20. script>
    21. body>
    22. html>

    9、事件解绑

    1. <button>dom1button>
    2. <button>dom2button>

    对dom 0 级进行解绑

    1. const btn=document.querySelectorAll('button')
    2. btn[0].onclick=function() {
    3. alert('dom1')
    4. btn[0].onclick='null' //解绑dom 0 级
    5. }

    对dom 2级进行解绑

    1. const btn=document.querySelectorAll('button')
    2. function f(){
    3. alert('dom2')
    4. btn[1].removeEventListener('click',f) //dom2 级 解绑
    5. }
    6. btn[1].addEventListener('click',f)

    10、窗口加载事件

    window加载事件:等页面元素全部加载完成才执行onload里面的代码

    窗口加载   onload 文档全部加载完毕包括css图片js等资源

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

    DOMContentLoaded 当dom元素加载完毕就执行,不必等其他资源加载完(加载速度快)

    1. window.addEventListener( 'DOMContentLoaded' , function ( ){ } )

    11、窗口尺寸事件

    1. window.addEventListener( ' resize',function( ) {
    2. console.log('窗口大小改变了');
    3. console.log(document.documentElement.clientWidth) //获取屏幕尺寸
    4. })

    12、元素尺寸和位置

    元素尺寸或位置     client   offset   尺寸             scroll  位置

        clientWidth    内容宽+左右 padding
        clientHeight   内容高+上下 padding

        offsetWidth    带边框的 clientWidth            内容宽+左右padding+左右border

        
         scrollWidth     实际内容区域(包括隐藏的内容)

         offsetLeft / offsetTop 

         offsetLeft   距离参照物(以最近的带有定位的祖先元素,没有则参照物文档)左侧距离
     

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8" />
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    7. <title>Documenttitle>
    8. <style>
    9. * {
    10. padding: 0;
    11. margin: 0;
    12. }
    13. .wrapper {
    14. width: 300px;
    15. height: 300px;
    16. background-color: red;
    17. padding: 20px;
    18. border: 6px dashed black;
    19. margin-left: 100px;
    20. position: relative;
    21. }
    22. .wrapper .box {
    23. width: 100px;
    24. height: 100px;
    25. background-color: blue;
    26. margin: 0 auto;
    27. border: 2px solid green;
    28. padding: 10px;
    29. overflow: hidden;
    30. white-space: nowrap;
    31. }
    32. style>
    33. head>
    34. <body>
    35. <div class="wrapper">
    36. <div class="box">
    37. 内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容
    38. div>
    39. div>
    40. <script>
    41. const wrapper_box=document.querySelector('.wrapper')
    42. const box=document.querySelector('.box')
    43. console.log(wrapper_box.clientWidth)//340
    44. console.log(wrapper_box.clientHeight)//340
    45. console.log(box.clientHeight)//120
    46. console.log(box.clientWidth)//120
    47. console.log('=======================')
    48. console.log(wrapper_box.offsetWidth)//352
    49. console.log(wrapper_box.offsetHeight)//352
    50. console.log(box.offsetHeight)//123
    51. console.log(box.offsetWidth)//123
    52. console.log('===========================')
    53. console.log(box.scrollWidth)//596
    54. console.log(box.offsetTop)//20
    55. console.log(box.offsetLeft)//108
    56. script>
    57. body>
    58. html>

    13、窗口滚动事件

    1. window.addEventListener( 'scroll', function( ) {
    2. console.log(document.documentElement.scrollTop)//页面被卷去的尺寸
    3. })

    14、日期对象

    方法:

    getFullYear 获取四位年份

    getMonth 获取月份,取值为 0 ~ 11

    getDate 获取月份中的每一天,不同月份取值也不相同

    getDay 获取星期,取值为 0 ~ 6

    getHours 获取小时,取值为 0 ~ 23

    getMinutes 获取分钟,取值为 0 ~ 59

    getSeconds 获取秒,取值为 0 ~ 59

    时间戳是指1970年01月01日00时00分00秒起至现在的总秒数或毫秒数,它是一种特殊的计量时间的方式。

    获取时间戳的方法,分别为 getTime 和 Date.now 和 +new Date()  

    1. // 1. 实例化
    2. const date = new Date()
    3. // 2. 获取时间戳
    4. console.log(date.getTime())
    5. // 还有一种获取时间戳的方法
    6. console.log(+new Date())
    7. // 还有一种获取时间戳的方法
    8. console.log(Date.now())

     15、节点

    查找节点


        1.通过节点关系查找元素     元素.parentNode

        2.子节点     元素.children      伪数组    本质是对象  {0:... ,1:***, length : 20}

        元素.childNodes    所有儿子,包括文本节点    可以获取文本换行

        3.兄弟节点
        previousSibling   了解   打印的是文本(比如换行)
        previousElementSibling    上一个兄弟
        nextElementSibling    下一个兄弟

    插入节点

    • createElement 动态创建任意 DOM 节点

    • cloneNode 复制现有的 DOM 节点,传入参数 true 会复制所有子节点

    • appendChild 在末尾(结束标签前)插入节点

    • insertBefore 在父节点中任意子节点之前插入新节点

    • prepend(添加的元素)     在父元素的第一个子元素之前添加    每次在前面加

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8" />
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    7. <title>Documenttitle>
    8. <style>
    9. .box {
    10. margin: 50px auto;
    11. width: 300px;
    12. position: relative;
    13. }
    14. img {
    15. width: 300px;
    16. }
    17. .box span {
    18. font-size: 20px;
    19. position: absolute;
    20. right: 0;
    21. top: 0;
    22. display: block;
    23. width: 30px;
    24. height: 30px;
    25. text-align: center;
    26. cursor: pointer;
    27. }
    28. style>
    29. head>
    30. <body>
    31. <div class="box">
    32. <img src="./3.webp" alt="" />
    33. <span class="close">✖️span>
    34. div>
    35. <ul>
    36. <li>中国li>
    37. <li>韩国li>
    38. <li>朝鲜li>
    39. <li>缅甸li>
    40. ul>
    41. <textarea name="" id="" cols="30" rows="10">textarea>
    42. <button>发布评论button>
    43. <ul class="comment">ul>
    44. <script>
    45. // 节点操作 (增 删 改 查)
    46. //通过节点关系查找元素 父亲 1 元素.parentNode
    47. document.querySelector('.close').addEventListener('click', function () {
    48. this.parentNode.style.display = 'none'
    49. })
    50. // 2 获取子节点 元素.children
    51. const ul = document.querySelector('ul')
    52. console.log(Array.isArray(ul.children))
    53. console.log(ul.children) // 伪数组 本质是对象 {0:...,1:***, length:20}
    54. console.log(ul.childNodes) // 了解 所有儿子 包括文本节点
    55. for (let i = 0; i < ul.children.length; i++) {
    56. console.log(ul.children[i])
    57. }
    58. // 3 兄弟节点
    59. const country = document.querySelector('ul li:nth-child(2)')
    60. console.log(country.previousSibling) // 了解
    61. console.log(country.previousElementSibling) // 上一个兄弟
    62. console.log(country.nextElementSibling) // 下一个兄弟
    63. // 获取相关元素
    64. const tarea = document.querySelector('textarea')
    65. const btn = document.querySelector('button')
    66. const comment = document.querySelector('.comment')
    67. // 注册事件
    68. btn.addEventListener('click', function () {
    69. // 1 获取文本域内容
    70. let txt = tarea.value.trim()
    71. if (txt === '') return
    72. // 检测敏感词汇 sb
    73. let index = txt.indexOf('sb')
    74. while (index !== -1) {
    75. txt = txt.replace('sb', '**')
    76. index = txt.indexOf('sb')
    77. }
    78. // 2 创建元素
    79. const li = document.createElement('li')
    80. li.innerHTML = txt
    81. // 3 把li添加到ul
    82. // comment.appendChild(li)
    83. comment.append(li)
    84. //comment.prepend(li) // 在父元素的第一个子元素之前添加
    85. // 4 清空文本域
    86. tarea.value = ''
    87. })
    88. script>
    89. body>
    90. html>

    删除节点

         元素.remove( )

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8" />
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    7. <title>Documenttitle>
    8. head>
    9. <body>
    10. <div class="box">
    11. <ul>
    12. <li>111li>
    13. <li>222li>
    14. ul>
    15. div>
    16. <button>删除button>
    17. <script>
    18. // 删除元素 元素.remove()
    19. const ul = document.querySelector('ul')
    20. // ul.children[1].remove() '自杀' -> DOM树上不存在该元素
    21. // ul.removeChild(ul.children[1]) 父亲删除孩子
    22. // ul.children[1].style.display = 'none' // -> 元素隐藏,DOM树上还存在
    23. document.querySelector('button').addEventListener('click', function () {
    24. const r = confirm('你确定要删除吗?') // 提示确认框
    25. r && ul.children[1].remove()
    26. })
    27. script>
    28. body>
    29. html>

    16、鼠标移入事件

     mouseover   会冒泡

    mouseenter   不会冒泡
    移动端
    touchstart   触摸开始
    touchmove   触摸移动
    touchend   触摸结束
     

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8" />
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    7. <title>Documenttitle>
    8. <style>
    9. .box {
    10. width: 300px;
    11. height: 300px;
    12. background-color: red;
    13. }
    14. .son {
    15. width: 140px;
    16. height: 140px;
    17. background-color: skyblue;
    18. margin: auto;
    19. }
    20. style>
    21. head>
    22. <body>
    23. <div class="box">
    24. div>
    25. <script>
    26. // mouseennter(推荐用) mouseover
    27. // const box = document.querySelector('.box')
    28. // const son = box.children[0]
    29. // box.addEventListener('mouseenter', function () {
    30. // alert('父亲')
    31. // })
    32. // son.addEventListener('mouseenter', function () {
    33. // alert('儿子')
    34. // })
    35. let startX = 0
    36. document
    37. .querySelector('.box')
    38. .addEventListener('touchstart', function (e) {
    39. startX = e.changedTouches[0].pageX
    40. console.log('触摸开始')
    41. })
    42. document
    43. .querySelector('.box')
    44. .addEventListener('touchmove', function (e) {
    45. const diff = e.changedTouches[0].pageX - startX
    46. console.log(diff > 0 ? '右滑' : '左滑')
    47. console.log('一直触摸')
    48. })
    49. document.querySelector('.box').addEventListener('touchend', function () {
    50. console.log('触摸结束')
    51. })
    52. script>
    53. body>
    54. html>

  • 相关阅读:
    LightDB - libpq支持匿名块绑定参数
    Antv/G2 柱状图添加自定义点击事件
    雷达人体存在感应器方案,智能物联网感知技术,实时感应人体存在
    线上环境不要使用console.log,会导致页面卡顿,内存泄漏的原因
    MYSQL 使用基础 - 这么用就对了
    Hypervisor Platform无法执行xmm寄存器fpu指令sse解决方法
    Linux C语言实现通过socket发送数据,C语言测试socket以太网网速。recv函数的一些不足。
    vue购物车实战
    2022年最新安徽建筑安全员考试题库及答案
    多尺度特征融合
  • 原文地址:https://blog.csdn.net/m0_56713342/article/details/134406473