【问题标题】:What is the difference between mouseover & onmouseover in JavaScript?JavaScript 中的 mouseover 和 onmouseover 有什么区别?
【发布时间】:2021-09-19 21:06:32
【问题描述】:

我是一名 JavaScript 程序员新手。有人可以让我理解这是如何工作的吗?

JavaScript 中的mouseoveronmouseover 有什么区别?我们可以互换它的用途吗?如果不是,我们怎么知道在哪里使用哪一个?

mouseover 示例:

function showAlert() {}
button.addEventListener('mouseover', showAlert);

onmouseover 示例:

function changeColor() {} 
titleHeader.onmouseover = changeColor;

【问题讨论】:

    标签: javascript dom-events mouseevent mouseover onmouseover


    【解决方案1】:

    根据他们所做的工作,他们基本上都是相同的,但是当我们谈论所做的事情时,就会出现差异。您可以根据自己的意愿使用其中的任何一个,但 Internet Explorer 8 和更早版本不支持 addEventListener() 方法,当您想要使用鼠标悬停时需要此方法。 作为 dom 元素的 addEventListener() 的语法是 addEventListener(事件,函数)

    event(required)-> 指定事件名称的字符串。 注意:不要使用“on”前缀。例如,使用“mouseover”而不是“mouseover”。 function(required)->指定事件发生时要运行的函数。 例如:

        <html>
        <body>
    
        <p>This example uses the addEventListener() method to attach a "mouseover" and "mouseout" event to a h1 element.</p>
    
        <h1 id="demo">Mouse over me</h1>
    
        <script>
        document.getElementById("demo").addEventListener("mouseover", mouseOver);
        function mouseOver() {
        document.getElementById("demo").style.color = "red";
        }
        </script>
        </body>
        </html>
    **Dom Event onmouseover**
        <body>
        <h1 id="demo">Mouse over me</h1>
        <script>
        document.getElementById("demo").onmouseover = function(){mouseOver()};
    
        function mouseOver() {
         document.getElementById("demo").style.color = "red";
        }
        </script>
        </body>
    

    最后我想补充一点,你可以在脚本中使用 addEventListener ,但你不能在你的 html 正文中使用它,但是如果发生 Dom 事件,你可以在 html 中使用它,也可以使用类似的语法 例如:

        <html>
        <body>
        <p>This example demonstrates how to assign an "onmouseover" and "onmouseout" 
        event to a h1 element.</p>
        <h1 id="demo" onmouseover="mouseOver()" >Mouse over me</h1>
        <script>
        function mouseOver() {
         document.getElementById("demo").style.color = "red";
        }
        </script>
    

    【讨论】:

    • 非常感谢您的回答。我相信第 2 段有一些错误。请您确认一下吗?
    • 不正确输入你可以问你的疑问然后我会尝试解决这个问题
    • 如果我错了,请纠正我。我只是对这部分感到困惑:在第二段中,它反映了,'不要使用“on”前缀。例如,使用“mouseover”而不是“mouseover”。'
    猜你喜欢
    • 2010-11-09
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 2011-06-28
    • 2010-12-10
    • 2010-09-19
    • 2010-10-29
    相关资源
    最近更新 更多