程序员鸡皮

文章 分类 评论
60 3 9

站点介绍

一名PHP全栈程序员的日常......

重学Javascript基础(十) DOM中的事件处理

abzzp 2024-10-07 161 0条评论 前端 JavaScript

首页 / 正文
本站是作为记录一名北漂程序员编程学习以及日常的博客,欢迎添加微信BmzhbjzhB咨询交流......

发布于2024-07-04

01.事件处理的方案选择

<!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>
    <!-- 直接在html中编写JavaScript代码(了解) -->
     <button onclick="console.log('按钮1发生了点击~')">按钮1</button>
     <button class="btn2">按钮2</button>
     <button class="btn3">按钮3</button>

     <script>
        // 1.获取元素对象
        var btn2El = document.querySelector(".btn2")
        var btn3El = document.querySelector(".btn3")

        // 2.onclick属性
        function handleClick01(){
            console.log("按钮2发生了点击~")
        }
        function handleClick02(){
            console.log("按钮2的第二个处理函数")
        }
        btn2El.onclick = handleClick01
        btn2El.onclick = handleClick02

        // 3.addEventListener(推荐)
        btn3El.addEventListener("click",function(){
            console.log("第一个btn3的事件监听~")
        })
        btn3El.addEventListener("click",function(){
            console.log("第二个btn3的事件监听~")
        })
        btn3El.addEventListener("click",function(){
            console.log("第三个btn3的事件监听~")
        })
     </script>
</body>
</html>

02.事件冒泡和事件捕获

<!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>
        .box {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 200px;
          height: 200px;
          background-color: orange;
        }
    
        .box span {
          width: 100px;
          height: 100px;
          background-color: red;
        }
      </style>
</head>
<body>
    <div class="box">
        <span></span>
    </div>

    <script>
        // 1.获取元素
        var spanEl = document.querySelector("span")
        var divEl = document.querySelector("div")
        var bodyEl = document.body

        // 2.绑定点击事件
        // spanEl.onclick = function(){
        //     console.log("span元素发生了点击~")
        // }
        // divEl.onclick = function(){
        //     console.log("div元素发生了点击~")
        // }
        // bodyEl.onclick = function(){
        //     console.log("body元素发生了点击~")
        // }

        // 默认情况下是事件冒泡
        spanEl.addEventListener("click",function(){
            console.log("span元素发生了点击~冒泡")
        })
        divEl.addEventListener("click",function(){
            console.log("div元素发生了点击~冒泡")
        })
        bodyEl.addEventListener("click",function(){
            console.log("body元素发生了点击~冒泡")
        })

        // 设置希望监听事件捕获的过程
        spanEl.addEventListener("click",function(){
            console.log("span元素发生了点击~捕获")
        },true)
        divEl.addEventListener("click",function(){
            console.log("div元素发生了点击~捕获")
        },true)
        bodyEl.addEventListener("click",function(){
            console.log("body元素发生了点击~捕获")
        },true)
    </script>
</body>
</html>

03.事件对象的属性解析

<!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>
        .box {
          display: flex;
          width: 200px;
          height: 200px;
          background-color: orange;
        }
    
        span {
          width: 100px;
          height: 100px;
          background-color: #f00;
        }
      </style>
</head>
<body>
    <div class="box">
        <span class="btn">
          <button>按钮</button>
        </span>
      </div>
    
      <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
      <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
      <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
      <script>
        var divEl = document.querySelector("div")
        var btnEl = document.querySelector(".btn")

        // btnEl.onclick = function(){
        //     console.log("按钮发生了点击~")
        // }

        divEl.onclick = function(event){
            // 1.偶尔会使用
            console.log("事件类型:",event.type)
            console.log("事件阶段:",event.eventPhase)

            // 2.比较少使用
            console.log("事件元素中位置",event.offsetX,event.offsetX)
            console.log("事件客户端中位置",event.clientX,event.clientY)
            console.log("事件页面中位置",event.pageX,event.pageY);
            console.log("事件在屏幕中位置",event.screeX,event.screeY)

            // 3.target/currentTarget
            console.log(event.target)
            console.log(event.currentTarget)
            console.log(event.currentTarget === event.target)
        }
      </script>
</body>
</html>

04.事件对象的方法解析

<!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>
        .box {
          display: flex;
          width: 200px;
          height: 200px;
          background-color: orange;
        }
    
        .box span {
          width: 100px;
          height: 100px;
          background-color: #f00;
        }
      </style>
</head>
<body>
    <a href="http://www.baidu.com">百度一下</a>

    <div class="box">
      <span>
        <button>按钮</button>
      </span>
    </div>
    <script>
        // 1.阻止默认行为
        var aEl = document.querySelector("a")
        // aEl.onclick = function(event){
        //     console.log("a元素发生了点击~")
        //     event.preventDefault()
        // }

        // 2.阻止事件进一步传递
        var btnEl = document.querySelector("button")
        var spanEl = document.querySelector("span")
        var divEl = document.querySelector("div")

        divEl.addEventListener("click",function(event){
            console.log("div的事件捕获监听~")
            event.stopPropagation()
        },true)
        spanEl.addEventListener("click",function(){
            console.log("span的事件捕获监听~")
        },true)
        btnEl.addEventListener("click",function(event){
            console.log("button的事件捕获监听~")
            // event.stopPropagation()
        },true)

        divEl.addEventListener("click",function(){
            console.log("div事件的冒泡监听~")
            event.stopPropagation()
        })
        btnEl.addEventListener("click",function(){
            console.log("button的事件冒泡监听~")
        })
    </script>
</body>
</html>

05.事件处理函数中this

<!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>
    <div>
        <button>按钮</button>
      </div>
    <script>
        var btnEl = document.querySelector("button")
        var divEl = document.querySelector("div")

        divEl.onclick = function(event){
            console.log(this)
            console.log(event.currentTarget)
            console.log(divEl)
            console.log(this === divEl)
        }

        // divEl.addEventListener("click",function(){
        //     console.log(this)
        // })
    </script>
</body>
</html>

06.EventTarget-remove

<!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>
    <button>按钮</button>
    <script>
        var btnEl = document.querySelector("button")
        // // 1.将监听函数移除的过程
        // var foo = function(){
        //     console.log("监听到按钮的点击")
        // }
        // btnEl.addEventListener("click",foo)

        // // 需求:过5s钟后,将这个事件监听移除掉
        // setTimeout(function(){
        //     btnEl.removeEventListener("click",foo)
        // },5000)

        // 这种做法是无法移除的
        btnEl.addEventListener("click",function(){
            console.log("btn监听的处理函数~")
        })

        setTimeout(function(){
            btnEl.removeEventListener("click",function(){})
        },5000)

        // 举个例子
        // var obj1 = {name: "obj1"}
        // var obj2 = {name: "obj2"}
        // var obj3 = {name: "obj3"}
        // var arr = [obj1, obj2, obj3]

        // function removeArr(obj){
        //     var index = arr.findIndex(function(item){
        //         return item === {}
        //     })
        //     arr.splice(index,1)
        // }

        // removeArr({})
    </script>
</body>
</html>

07.EventTarget-dispatch

<!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>
    <script>
        // eventtarget就可以实现类似于事件总线的效果
        window.addEventListener("coderwhy",function(){
            console.log("监听到coderwhy的呼唤~")
        })

        setTimeout(function(){
            window.dispatchEvent(new Event("coderwhy"))
        },5000)
        
    </script>
</body>
</html>

08.事件委托-案例练习01

<!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>
        .active {
          color: red;
          font-size: 20px;
          background-color: orange;
        }
      </style>
</head>
<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>10</li>
      </ul>
    <script>
        // 1.每一个li都监听自己的点击,并且有自己的处理函数(自己的函数)
        // var liEls = document.querySelectorAll("li")
        // for(var liEl of liEls){
        //     // 监听点击
        //     liEl.onclick = function(event){
        //         event.currentTarget.classList.add("active")
        //     }
        // }

        // 2.统一在ul种监听
        var ulEl = document.querySelector("ul")
        ulEl.onclick = function(event){
            console.log("点击了某一个li",event.target)
            event.target.classList.add("active")
        }

        // 3.新需求:点击li变成active,其他的取消active
        var ulEl = document.querySelector("ul")
        var activeLiEl = null
        ulEl.onclick = function(event){
            // 1.将之前的active移除掉
            // for(var i = 0;i<ulEl.children.length;i++){
            //     var liEl = ulEl.children[i]
            //     if(liEl.classList.contains("active")){
            //         liEl.classList.remove("active")
            //     }
            // }

            // 1.找到active的li,移除掉active
            // var activeLiEl = ulEl.querySelector(".active")
            // if(activeLiEl){
            //     activeLiEl.classList.remove("active")
            // }

            // 1.变量记录的方式
            // edge case
            if(activeLiEl){
                activeLiEl.classList.remove("active")
            }

            // 2.给点击的元素添加active
            event.target.classList.add("active")
            
            // 3.记录最新的active对应的li
            activeLiEl = event.target
        }
    </script>
</body>
</html>

09.事件委托-案例练习02

<!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>
    <div class="box">
        <button data-action="search">搜索~</button>
        <button data-action="new">新建~</button>
        <button data-action="remove">移除~</button>
        <button>1111</button>
    </div>

    <script>
        var boxEl = document.querySelector(".box")
        boxEl.onclick = function(event){
            var btnEl = event.target
            var active = btnEl.dataset.action 
            switch(active){
                case "remove":
                    console.log("点击了移除按钮")
                    break
                case "new":
                    console.log("点击了新建按钮")
                    break
                case "search":
                    console.log("点击了搜索按钮")
                    break
                default:
                    console.log("点击了其他")
            }
        }
    </script>
</body>
</html>

10.鼠标事件-常见事件演练

<!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>
        .box{
            width: 200px;
            height: 200px;
            background-color: orange;
        }
    </style>
</head>
<body>
    <div class="box"></div>
    <script>
        // 鼠标事件
        var boxEl = document.querySelector(".box")

        boxEl.onclick = function(){
            console.log("click")
        }
        boxEl.oncontextmenu = function(event){
            console.log("点击了右键")
            event.preventDefault()
        }

        // 变量记录鼠标是否是点下去的
        var isDown = false
        boxEl.onmousedown = function(){
            console.log("鼠标按下去")
            isDown = true
        }

        boxEl.onmouseup = function(){
            console.log("鼠标抬起来")
            isDown = false
        }

        boxEl.onmousemove = function(){
            if(isDown){
                console.log("鼠标在div上面移动")
            }
        }
    </script>
</body>
</html>

11.鼠标事件-mouseenter和over

<!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>
        .box {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 200px;
          height: 200px;
          background-color: orange;
        }
    
        .box span {
          width: 100px;
          height: 100px;
          background-color: red;
        }
      </style>
</head>
<body>
    <div class="box">
        <span></span>
    </div>

    <script>
        var boxEl = document.querySelector(".box")
        var spanEl = document.querySelector("span")

        // 1.第一组
        boxEl.onmouseenter = function(){
            console.log("box onmouseenter")
        }
        boxEl.onmouseleave = function(){
            console.log("box onmouseleave")
        }

        spanEl.onmouseenter = function(){
            console.log("span onmouseenter")
        }
        spanEl.onmouseleave = function(){
            console.log("span onmouseleave")
        }

        // 第二组
        // boxEl.onmouseover = function(){
        //     console.log("box onmouseover")
        // }
        // boxEl.onmouseout = function(){
        //     console.log("box onmouseout")
        // }
    </script>
</body>
</html>

12.鼠标事件-enter和over应用

<!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>
        .box {
          background-color: orange;
        }
    
        .box button {
          flex: 1;
          height: 50px;
        }
      </style>
</head>
<body>
    <div class="box">
        <button>删除</button>
        <button>新增</button>
        <button>搜索</button>
      </div>
    <script>
        // 方案一:监听的本身就是button元素
        // var btnEls = document.querySelectorAll("button")
        // for(var i = 0;i<btnEls.length;i++){
        //     btnEls[i].onmouseover = function(event){
        //         console.log(event.target.textContent)
        //     }
        // }

        // 方案二:事件委托
        var boxEl = document.querySelector(".box")
        boxEl.onmouseover = function(event){
            console.log(event.target.textContent)
        }
    </script>
</body>
</html>

13.键盘事件-常见事件演练

<!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>
    <input type="text">
    <button>搜索</button>
    <script>
        var inputEl = document.querySelector("input")
        var btnEl = document.querySelector("button")

        // inputEl.onkeydown = function(){
        //     console.log("onkeydown")
        // }
        // inputEl.onkeypress = function(){
        //     console.log("onkeypress")
        // }
        // inputEl.onkeyup = function(event){
        //     console.log(event.key,event.code)
        // }

        // 1.搜索功能
        btnEl.onclick = function(){
            console.log("进行搜索功能",inputEl.value)
        }

        inputEl.onkeyup = function(event){
            if(event.code === "Enter"){
                console.log("进行搜索功能",inputEl.value)
            }
        }

        // 2.按下s的时候,搜索自动获取焦点
        document.onkeyup = function(event){
            if(event.code === "KeyS"){
                inputEl.focus()
            }
        }
    </script>
</body>
</html>

14.表单事件-常见事件演练

<!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="/abc">
        <input type="text">
        <textarea name="" id="" cols="30" rows="10"></textarea>
    
        <button type="reset">重置</button>
        <button type="submit">提交</button>
      </form>
      <script>
        var inputEl = document.querySelector("input")

        // // 1.获取焦点和失去焦点
        // inputEl.onfocus = function(){
        //     console.log("input获取到了焦点")
        // }
        // inputEl.onblur = function(){
        //     console.log("input失去了焦点")
        // }

        // // 2.内容发生改变/输入内容 
        // // 输入的过程:input
        // // 内容确定发生改变(离开):change
        inputEl.oninput = function(){
            console.log("input事件正在输入内容",inputEl.value)
        }
        inputEl.onchange = function(){
            console.log("change事件内容发生改变",inputEl.value)
        }

        // 3.监听重置和提交
        var formEl = document.querySelector("form")
        formEl.onreset = function(event){
            console.log("发生了重置事件")
            event.preventDefault()
        }
        formEl.onsubmit = function(event){
            console.log("发生了提交事件")
            // axios库提交
            event.preventDefault()
        }
      </script>
</body>
</html>

15.加载事件-文档加载监听

<!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>
        .box {
          width: 200px;
          height: 200px;
        }
      </style>
</head>
<body>
    <script>
        // 注册事件监听
        window.addEventListener("DOMContentLoaded",function(){
            // 1.这里可以操作box,box已经加载完毕
            // var boxEl = document.querySelector(".box")
            // boxEl.style.backgroundColor = "orange"
            // console.log("HTML内容加载完毕")

            // 2.获取img对应的图片的宽度和高度
            var imgEl = document.querySelector("img")
            console.log("图片的宽度和高度:",imgEl.offsetHeight,imgEl.offsetHeight)
        })

        window.onload = function(){
            console.log("文档中所有资源都加载完毕")
            // var imgEl = document.querySelector("img")
            // console.log("图片的宽度和高度:",imgEl.offsetWidth,imgEl.offsetHeight)
        }

        window.onresize = function(){
            console.log("创建大小发生改变时")
        }
    </script>
</body>
</html>

感谢大家观看,我们下次见

评论(0)

最新评论

  • abzzp

    十天看一部剧,还可以吧[[呲牙]]

  • ab

    @梦不见的梦 行,谢谢提醒,我优化一下

  • 梦不见的梦

    网站的速度有待提升,每次打开都要转半天还进不来呢

  • abzzp

    @React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?[[微笑]]

  • abzzp

    @Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品[[发呆]]

  • Teacher Du

    我们大学那会,献血还给学分~

  • @ab 我想去学网安,比如网警,但分也贼高😕

  • ab

    @夜 加油,你一样也可以成为程序员的,需要学习资料可以V我

  • 佬发布的好多技术文章似乎我只能评论这篇,真正的程序员!!哇塞 我也想去献血,过两年就成年了可以去献血了

日历

2024年11月

     12
3456789
10111213141516
17181920212223
24252627282930

文章目录

推荐关键字: vue JavaScript React Golang 观后感 ES6 读后感

站点公告
本站是作为记录一名北漂程序员编程学习以及日常的博客,欢迎添加微信BmzhbjzhB咨询交流......
点击小铃铛关闭
配色方案