web前端 --- js事件

js事件(event)

(js诞生就是基于事件驱动型编程)

(1)事件

用户通过各种行为(按键、鼠标点击、鼠标hover......)行为动作,引起相关 js 代码的执行。

事件的三元素:

  • 事件源:事件的被触发者,一般会绑定事件
  • 事件对象(event):这个对象包含了该事件相关的所有信息
  • 事件处理函数:处理事件的代码

<1> 定义事件(三种方式)

[1] DOM0模式:需html的标签onxxxx属性来配置

缺点:耦合了js和html,违背了w3c的三层分离原则;这种方式在事件处理函数中,拿不到事件对象;事件函数中的this指针指向winodw对象

ps:

test01(this)        //  绑定事件时,可以将this传递到事件函数中,事件函数需要传递这个this指针;

console.log(this)        //  而在function中的this直接指向了window对象

<!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">
    <script>
        function test01(node){
            alert("这里是美女,只不过你看不见")
        }
        // console.log(this);
        console.log(node);
        // node:事件源
    </script>
    <title>js事件</title>
</head>
<body>
    <button onclick="test01(this);">点击一下,你就知道</button>
    <!-- 双引号中,引入javascript代码 -->
</body>
</html>

[2] DOM2模式

主要涉及到两个方法,用于处理指定和删除事件处理程序的操作:addEventListener()removeEventListener()

  • 通过DOM对象,动态绑定事件
<!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>DOM2</title>
</head>
<body>
    <button id="box">美女不在这</button>
    
    <a href="#" class="msg">可以在这找找看</a>
    <a href="#" class="msg">可以在这找找看</a>

    <a href="#" class="sss">你喜欢美女吗</a>
    <a href="#" class="sss">你喜欢美女吗</a>
    <a href="#" class="sss">你喜欢美女吗</a>
    <a href="#" class="sss">你喜欢美女吗</a>
    <script>

        // DOM对象()
        let box = document.getElementById("box");

        // 通过DOM对象,动态绑定事件
        box.onclick = function (ev){
            // PS:动态绑定事件的方式,第一个参数就是事件对象
            alert("那美女在哪?")
            console.log(ev); // 事件对象
            console.log(ev.target); // 事件源
            console.log(this); // 事件源,这种事件中,this指向事件源
            console.log(`x轴坐标${ev.pageX},y轴坐标${ev.pageY}`)
            
        }

        // 用className单个绑定,需确定下标
        let msg = document.getElementsByClassName("msg");
        console.log(msg);
        msg[0].onclick = function(){
            alert("这里也没有美女。")
        }

        // 多个同时绑定,需采用循环
        let sss = document.getElementsByClassName("sss");
        for(let i = 0;i < sss.length;i++){
            sss[i].onclick = function(){
                alert(`md,我喜欢的不得了,这是我第${i + 1}个按钮`);
            }
        }
    </script>
</body>
</html>

  • 还有一种事件监听方式,绑定事件
<!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>
</head>
<body>

    <a href="http://www.baidu.com" id="go">百度</a>
    <button id="box">这里有个祢豆子</button>
    <script>
        let box = document.getElementById("box");
        // addEventListener:事件监听
        box.addEventListener("click",function(e){
            alert("点我干嘛");
            console.log(this);
            console.log(e.target);

            // 这个方法会取消冒泡 IE浏览器
            // e.cancelBubble();

            // 停止标签继续向上冒泡(阻止冒泡)  w3c
            // ev.stopPropagation();

        },true); // true:第三个参数true决定是否开启捕获流

        document.querySelector("#go").onclick = function(ev){

            alert("还是会去百度");
            // 阻止标签的默认行为
            ev.preventDefault();

        }
    </script>
</body>
</html>

[3] HTML事件处理程序

直接在HTML代码中添加事件处理程序

<input id= "btn" value= "按钮" type= "button" onclick= "showmsg();" >
  <script>
   function showmsg(){
   alert( "HTML添加事件处理" );
   }
  </script>

<2> 事件流的分类

冒泡流:冒泡即事件最开始由最具体的元素(文档中嵌套层次最深的那个节点)接收,然后逐级向上传播至最不具体的节点(文档)

捕获流:捕获即事件最早由不太具体的节点接收,而最具体的节点最后接收到事件。

(2)常见的事件

事件 内容
onabort 图像加载被中断
onblur 元素失去焦点
onchange 用户改变域内容
ondblclick 鼠标双击某个对象
onerror 当加载文档或图像时发生某个错误
onfocus 元素获得焦点
onkeydown 某个键盘的键被按下
onkeypress 某个键盘的键被按下或按住
onkeyup 某个键盘的键被松开
onload 某个页面或图像完成加载
onmousedown 某个鼠标按键被按下
onmousemove 鼠标被移动
onmouseout 鼠标从某元素被移开
onmouseover 鼠标被移到某元素之上
onmouseup 某个鼠标按键被松开
onreset 重置按钮被点击
onresize 窗口或框架被调整尺寸
onselect 文本被选定
onsubmit 提交按钮被点击
onunload 用户退出页面

(3)代码示例:

例1:抽奖

<!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">
    <style >
        * {
            margin: 0;
            padding: 0;
        }
        .container {
            width: 800px;
            height: 800px;
            border: 1px dashed rebeccapurple;
            position: absolute;
            left: 50%;
            margin-left: -400px;
            text-align: center;
            line-height: 100px;
        }
        .container .box, .box2 {
            width: 300px;
            height: 300px;
            background: greenyellow;
            border-radius: 50%;
            margin: auto;
            margin-top: 50px;
            text-align: center;
            line-height: 300px;
        }
        .box2 {
            background: deepskyblue;
        }
        #show {
            font-size: 30px;
            color: white;
            font-weight: bold;
        }
        #start {
            width: 300px;
            height: 50px;
            background: palegreen;
        }
    </style>
    <title>抽奖</title>
</head>
<body>
    <div class="container">
        <div class="box" id="box">
            <span id="show">
                小礼品
            </span>
        </div>
        <button id="start" onclick="start()">点击开始</button>
    </div>

    <script>
        let start = document.querySelector("#start");
        let show = document.querySelector("#show");
        let timer = null;
        let box = document.querySelector("#box");
        let isStop = false;
        let nums = ["iphone14","100w","1000w","杯子","大花棉袄","充电宝","欠我五元","谢谢惠顾"];

        start.onclick = function(){
            if(!isStop){
                isStop = true;
                timer = setInterval(function(){
                let index = Math.floor(Math.random()*nums.length);
                show.innerHTML = nums[index];
                box.className = "box2";
                start.textContent = "停止抽奖";
            },100);
            } else{
                isStop = false;
                window.clearInterval(timer);
                box.className = "box";
                start.textContent = "开始抽奖";

            }

        }
    </script>

</body>
</html>

例2:div的拖动

<!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">
    <style>
        .box{
            width: 150px;
            height: 150px;
            border: 1px dashed rosybrown;
            position: absolute; /* 进行绝对定位 */
            left: 300px;
            top: 200px;

        }
    </style>
    <title>div的拖动</title>
</head>
<body>
    <div class="box"></div>

    <script>
        let _box = document.querySelector(".box");
        _box.onmousedown = function(e){
            let x = e.pageX-_box.offsetLeft;
            let y = e.pageY-_box.offsetTop;

            document.onmousemove = function(ev){
                let x2 = ev.pageX - x;
                let y2 = ev.pageY - y;

                _box.style.left = x2 + "px";
                _box.style.top = y2 + "px";

            }
        }
        _box.onmouseup = function(){
            document.onmousemove = null;
        }
    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_62443409/article/details/131027383