当前位置: 首页 > article >正文

JavaScript 事件处理

一、简介

​ 事件:发生在HTML元素上的事情,可以是用户的行为,也可以是浏览器的行为,如

  • 用户点击了某个HTML元素
  • 用户将鼠标移动到某个HTML元素上
  • 用户输入数据时光标离开
  • 页面加载完成

事件源:事件触发的源头,即触发事件的元素,如按钮、输入框、超链接等

事件对象:当一个事件发生时,这个事件相关的详细信息会被保存到一个对象中,称为event对象

事件监听:监听事件的发生,绑定事件函数,当事件被触发后执行该事件函数,即回调函数

二、绑定事件

​ 三种方式:

  • 静态绑定,通过为标签的事件属性赋值
<head>    
    <script>
        function f1(){
            console.log("静态绑定");
        }
    </script>
</head>
<body>
    <!--方式1:通过标签的事件属性-->
    <button onclick="f1()">按钮1</button>
</body>
  • 动态绑定,通过为DOM对象的事件属性赋值
<head>
   <script>
        //当页面加载完成后执行
        window.onload=function(){
            var btn2=document.getElementById("btn2");
            //方式2:通过DOM对象的事件属性,为按钮绑定点击事件
            btn2.onclick=function(){
                console.log("动态绑定");
            }
        }
    </script>
</head>
<body>
    <button id="btn2">按钮2</button>
</body>
  • 动态绑定,通过为DOM对象进行事件监听,使用addEventListene("事件名",回调函数)
<head>   
   <script>
        //当页面加载完成后执行
        window.onload=function(){
            //方式3:通过为DOM对象进行事件监听addEventListener
            var btn3=document.getElementById("btn3");
            btn3.addEventListener("click",function(){
                console.log("动态绑定");
            });
           
        }
    </script>
</head>
<body>
    <button id="btn3">按钮3</button>
</body>

 注意:

  • 可以通过事件回调函数的第一个参数获取事件对象event,属性含义:
    target      事件的目标元素,即事件源
    type            事件类型
    timeStamp   事件生成的日期和时间
    clientX     当事件被触发时,鼠标指针的水平坐标
    clientY     当事件被触发时,鼠标指针的垂直坐标
  • 在事件回调函数中,this表示事件源,即发生事件的元素 
<head>
     <script>
        //当页面加载完成后执行
        window.onload=function(){
            var btn=document.getElementById("btn");
            btn.onclick=function(event){//事件触发时会自动为回调函数传入一个参数,表示event事件对象
                console.log(111);
                console.log(event);
                console.log(typeof event);
                console.log(event.target);//事件源
                console.log(event.type);//事件类型
                console.log(this);//事件源,等同于console.log(event.target);
            }
        }
        function f1(event){
           console.log(event);
        }
    </script>
</head>
<body>
    <button id="btn">点我</button>
    <!--静态绑定事件时,需要在绑定事件回调函数时接收事件对象参数-->
    <button onclick="f1(event)">click me</button>
</body>

 三、常用事件

1、鼠标事件

事件名描述
onclick鼠标单击
ondblclick鼠标双击
onmouseover鼠标移到某元素之上
onmouseout鼠标从某元素上移开
onmousedown鼠标按钮被按下
onmouseup鼠标按键被松开
onmousemove鼠标被移动
oncontextmenu鼠标右键单击
<head>
     <script>
        window.onload=function(){
            var btn=document.getElementById("btn");
            //鼠标事件
            //btn.onclick=function(){}//鼠标单击
            //btn.ondblclick=function(){}//鼠标双击
            /*btn.onmouseover=function(){//鼠标经过
                console.log(111);
            }
            btn.onmouseout=function(){//鼠标离开
                  console.log(222);
            }
            btn.onmousedown=function(){//鼠标按下
                console.log(111);
            }
            btn.onmouseup=function(){//鼠标松开
                  console.log(222);
            }
            btn.onmousemove=function(){//鼠标移动
                console.log(111);
            }*/
            btn.oncontextmenu=function(){//鼠标右击
                console.log(111);
            }
        }
    </script>
</head>
<body>
    <button id="btn">点我</button>
</body>

2、键盘事件

事件名描述
onkeydown某个键盘的键被按下去
onkeypress某个键盘的键被按下去且松开
onkeyup某个键盘的键被松开
<head>     
     <script>
          //键盘事件
            var username=document.getElementById("username");
            username.onkeydown=function(e){//键盘的键被按下去
                //console.log(111);
                //console.log(e.keyCode);//获取按键码
                if(e.keyCode==13){//当输入回车后才会输出111(回车键码是13)
                    console.log(111);
                }
            }
            /*username.onkeypress=function(){//键盘的键被按下去且松开
                console.log(222);
            }
            username.onkeyup=function(){//键盘的键被松开
                console.log(333);
            }*/
            
        }
    </script>
</head>
<body>
    用户名:<input type="text" id="username"> 
</body>

3、表单事件

事件名描述
onfocus元素获得焦点
onblur元素失去焦点
onchange域的内容发生改变,一般用于文件选择器和下拉列表
onselect文本内容被选中
onsubmit表单提交前触发,回调函数返回true表示允许表单提交,返回false表示阻止表单提交

表单元素的方法:focus()、blur()、select()、click()

<head>
    <style>
        #username,#email{
            outline: 0;
        }
        .border{
            border: 1px solid red;

        }
        #img{
            width:100px;
            height:100px;
        }
        #head{
            display:none;
        }
        /*被选中的内容为红色*/
        /*#email::selection{
            color:red;
        }*/
    </style>
    <script>
        //表单事件
        window.onload=function(){
            var username=document.getElementById("username");
            username.onfocus=function(){//元素获得焦点
                username.classList.add("border");
            }
            username.onblur=function(){//元素失去焦点
                username.classList.remove("border");
            }
            document.getElementById("eat").onchange=function(){//域的内容发生改变
                console.log(this.checked);//获取是否选中
            }
            document.getElementById("head").onchange=function(){
                //console.log(this.files);//获取选择的文件数据
                document.getElementById("img").src=window.URL.createObjectURL(this.files[0]);//根据选中的图片改src
            }
            document.getElementById("email").onselect=function(){//文本内容被选中
                 this.classList.add("border");
            }
            document.getElementById("frm").onsubmit=function(){
                //判断表单内容是否符合要求
                var email=document.getElementById("email").value;
                if(email==""){
                    return false;
                }
                return true;
            }

        }

    </script>
</head>
<body>
    <form action="" id="frm">
        用户名:<input type="text" id="username"><br>
        爱好:<input type="checkbox" name="hobby" id="eat" value="eat">吃饭<br>
        头像:<input type="file"  id="head" multiple><!--可同时选多个文件-->
        <label for="head">
            <img src="./默认头像.png" id="img">
        </label><br>
        邮箱:<input type="text" id="email" value="tom@sina.com.cn" name="email"><br>
        <input type="submit" value="提交">
    </form>
</body>

四、事件操作

1、事件流

概念:当一个HTML元素产生事件时,该事件会在当前元素与根元素之间按特定的顺序传播,所有经过的节点都会收到该事件并执行,这个传播过程就是DOM事件流。

​ 分类:事件冒泡、事件捕获

2、事件冒泡/事件捕获

事件冒泡:当一个元素上的事件被触发时,事件从事件源开始,往上冒泡直到页面的根元素,这一过程被称为事件冒泡(默认方式)

事件捕获:当一个元素上的事件被触发时,事件从页面的根元素开始,往下直到事件目标元素,这一过程被称为事件捕获

阻止事件冒泡 :event.stopPropagation()

<head>
     <style>
        div{
            border:1px solid black;
        }
        #div1{
            width:200px;
            height:200px;
        }
        #div2{
            width:150px;
            height:150px;
        }
        #div3{
            width:100px;
            height:100px;
        }
        #div4{
            width:50px;
            height:50px;
        }
    </style>
    <script>
        function $(id){
            return document.getElementById(id);
        }
        window.onload=function(){
            $("div1").addEventListener("click",function(){
                console.log("div1");
            },false)//第三个参数为true表示采用事件捕获,默认为false表示事件冒泡
            $("div2").addEventListener("click",function(){
                console.log("div2");
            },false)
            $("div3").addEventListener("click",function(event){
                console.log("div3");
                event.stopPropagation();//阻止事件传播
            },false)
            $("div4").addEventListener("click",function(){
                console.log("div4");
            },false)
        };
    </script>
</head>
<body>
    <div id="div1" onclick="print(' div1' )">div1
        <div id="div2" onclick="print(' div2' )">div2
            <div id="div3" onclick="print(' div3' )">div3
                <div id="div4" onclick="print(' div4' )">div4</div>
            </div>
        </div>
    </div>
</body>

 3、事件代理/事件委托

​ 概念:利用事件冒泡/事件捕获机制,通过给父元素绑定事件,从而实现对所有子元素的事件管理,无需为每个子元素绑定事件

​ 优点:1.减少事件注册,降低内存占用

​            2.新增元素时实现动态绑定事件

<head>     
     <style>
        ul{
            border:1px solid #ccc;
        }
        li{
            background: pink;
        }
    </style>
    <script>
        window.onload=function(){
            /*var lis=document.querySelectorAll("li");
            for(var li of lis){
                li.onclick=function(){
                    console.log(this);//事件源
                    console.log(this,innerText);
                }
            }*/
           document.querySelector('ul').onclick=function(e){
            console.log(e.target.innerText);
            //console.log(e.target);//触发事件的原始对象
            console.log(this);
           }
        }
        function add(){
            var li=document.createElement("li");
            li.innerText="li6";
            /*li.onclick=function(){
                    console.log(this,innerText);
                }*/
            document.querySelector('ul').appendChild(li);
        }
    </script>
</head>
<body>

    <button onclick="add()">添加li</button>
    <ul>
        <li>li1</li>
        <li>li2</li>
        <li>li3</li>
        <li>li4</li>
        <li>li5</li>
    </ul>
</body>

4、事件默认行为

​ 概念:当一个事件发生时浏览器自己会默认做的事情,如:点击链接时默认会跳转,右键点击时默认会弹出菜单

​ 阻止事件的默认行为:e.preventDefault();

<head> 
    <script>
        function print(e){
            console.log(111);
            e.preventDefault();//阻止事件的默认行为
        }

    </script>
</head>
<body>
    <button oncontextmenu="print(event)">右键点击</button><br>
    <a href="https://www.baidu.com" onclick="print(event)">百度</a>
    <!--<a href="JavaScript:print()">百度</a>-->
</body>

 


http://www.kler.cn/news/306903.html

相关文章:

  • Gateway Timeout504: 网关超时的完美解决方法
  • 【鸿蒙OH-v5.0源码分析之 Linux Kernel 部分】005 - Kernel 入口 C 函数 start_kernel() 源码分析
  • 【Webpack--007】处理其他资源--视频音频
  • PostgreSQL - tutorial
  • 我的标志:奇特的头像
  • ARM驱动学习之21_字符驱动
  • Gitlab 中几种不同的认证机制(Access Tokens,SSH Keys,Deploy Tokens,Deploy Keys)
  • Linux线程同步:深度解析条件变量接口
  • Deep Learning-Based Object Pose Estimation:A Comprehensive Survey
  • VUE使用echarts编写甘特图(组件)
  • AI写作助力自媒体,传统模式将被颠覆
  • 网络安全学习(二)初识kali
  • SAP EWM Cross Docking (CD) 越库操作
  • 探索Python中的装饰器
  • 前端基础知识+算法(一)
  • 8- 【JavaWeb】用HTML和CSS来创建一个简洁的登录界面
  • OpenCV_图像像素读写操作
  • STM32_startup文件详解
  • 性能测试的复习4-数据库连接、控制器、定时器
  • 人脸防伪检测系统源码分享
  • 多线程下的共享变量访问数据竞争的问题
  • SSM框架学习
  • GD32E230 RTC报警中断功能使用
  • DockerDocker Compose安装(离线+在线)
  • 汽车免拆诊断案例 | 沃尔沃V40 1.9TD断续工作
  • ensp—相关ospf-3
  • SpringBoot 消息队列RabbitMQ 交换机模式 Fanout广播 Direct定向 Topic话题
  • react使用技巧
  • Spring6学习笔记4:事务
  • Spring Boot-消息队列相关问题