javascript中addEventListener和onclick的区别

先来看addEvenListener事件。

addEventListener() 方法用于向指定元素添加事件句柄。 提示: 使用 removeEventListener() 方法来移除
addEventListener() 方法添加的事件句柄。

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
   
</head>
<body>
    <button id="button1" >按键1</button>
    <p id="event">鼠标事件</p>
    <button id="button2">按钮2</button>
    <button id="button3">按钮3</button>
    <script>
        //请在此处编写代码
        /********** Begin **********/
        var x=document.getElementById("button1");
        x.addEventListener("mouseout", mouse_move);//鼠标移开事件
        x.addEventListener("mouseover", mouse_on);//鼠标聚焦事件
        x.addEventListener("click", mouse_click);//鼠标点击事件
        function mouse_move() {
            document.getElementById("event").innerHTML+="鼠标移开<br>";   //在p标签后添加html
        }
        function mouse_on() {
            document.getElementById("event").innerHTML+="鼠标聚焦<br>";
        }
        function mouse_click() {
            document.getElementById("event").innerHTML+="鼠标点击<br>";
        }
        /********** End **********/
    </script>
</body>
</html>

这里的button2可以使用addEventListener()同时监听多个事件。而且事件不会被覆盖。
注意:这里的script标签不能放在head里面,因为我们得先加载完html标签,才能使用监听事件。

拓展:mouseup ()当鼠标指针移动到元素上方,并松开鼠标左键时,会发生 mouseup 事件。
mousedown()当鼠标指针移动到元素上方,并按下鼠标左键时,会发生 mousedown 事件。
mouseenter ()当鼠标指针穿过(进入)被选元素时,会发生 mouseenter 事件。
mouseleave ()当鼠标指针离开被选元素时,会发生 mouseleave 事件


我们再来看看onclick()的使用

<!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>
    <p id="click_on">onclick</p>
    <script>
        var click1=document.getElementById("click_on");
        click1.onclick=function ()
        {alert("第一个click")};
        click1.onclick=function()
        {alert("第二个click")};
    </script>
</body>
</html>

这里只打印第二个click;表明使用多个onclick会被覆盖。

所以onclick和addEventListener事件区别是:onclick事件会被覆盖,而addEventListener可以先后运行不会被覆盖,addEventListener可以监听多个事件。

from:https://blog.csdn.net/qq_42444795/article/details/105264243

原文地址:https://www.cnblogs.com/youmingkuang/p/14984019.html