首页 文章

mouseover和mouseenter事件有什么区别?

提问于
浏览
139

我一直使用 mouseover 事件,但在阅读jQuery文档时,我找到了 mouseenter . 它们似乎完全相同 .

这两者之间是否存在差异?如果是,我应该何时使用它们?
(也适用于 mouseout vs mouseleave ) .

6 回答

  • 4

    只有Chrome可让您建议在点击包含动态生成内容的链接时使用的名称 . 但是,您可以在鼠标光标位于链接上时生成内容,并将其作为DATAURI放在标准静态href中 . 这将在右键单击菜单中启用“将链接另存为...”选项 .

    function download_content(a, side) 
    {
        a.innerHTML = "preparing content..";
    
        var txt = "call a function to generate content";
        var datauri = "data:plain/text;charset=UTF-8," + encodeURIComponent(txt);
        a.setAttribute('download', "chrome_let_you_suggest_a_name.txt");
        a.setAttribute('href', datauri);
    
        a.innerHTML = "content ready.";
    }
    document.getElementById('my_a_link').addEventListener('mouseover', function() { download_content(this); });
    
    <a id="my_a_link" href="#">save document</a>
    
  • -4

    您可以在the jQuery doc页面中尝试以下示例 . 这是一个很好的小型互动演示,它非常清晰,你可以亲自看看 .

    var i = 0;
    $("div.overout")
      .mouseover(function() {
        i += 1;
        $(this).find("span").text("mouse over x " + i);
      })
      .mouseout(function() {
        $(this).find("span").text("mouse out ");
      });
    
    var n = 0;
    $("div.enterleave")
      .mouseenter(function() {
        n += 1;
        $(this).find("span").text("mouse enter x " + n);
      })
      .mouseleave(function() {
        $(this).find("span").text("mouse leave");
      });
    
    div.out {
      width: 40%;
      height: 120px;
      margin: 0 15px;
      background-color: #d6edfc;
      float: left;
    }
    
    div.in {
      width: 60%;
      height: 60%;
      background-color: #fc0;
      margin: 10px auto;
    }
    
    p {
      line-height: 1em;
      margin: 0;
      padding: 0;
    }
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="out overout">
      <span>move your mouse</span>
      <div class="in">
      </div>
    </div>
    
    <div class="out enterleave">
      <span>move your mouse</span>
      <div class="in">
      </div>
    </div>
    

    简而言之,您会注意到当一个元素在它上面时会发生一个鼠标悬停事件 - 来自它的子OR或父元素,但只有当鼠标从该元素外部移动到该元素时才会发生鼠标输入事件 .

    as the mouseover() docs把它:

    [.mouseover()]会因事件冒泡而导致许多麻烦 . 例如,当鼠标指针在此示例中移动到Inner元素上时,鼠标悬停事件将被发送到该元素,然后逐渐渗透到外部 . 这可以在不合适的时间触发我们的绑定鼠标悬停处理程序 . 有关有用的替代方法,请参阅.mouseenter()的讨论 .

  • 0

    Mouseenter和mouseleave do not 对事件冒泡做出反应,而mouseover和mouseout do .

    这是描述行为的article .

  • 38

    对于像这样的问题通常都是如此,Quirksmode有the best answer .

    我想,因为jQuery的目标之一是使浏览器不可知,所以使用任一事件名称都会触发相同的行为 . 编辑:感谢其他帖子,我现在看到的情况并非如此

  • -4
    $(document).ready(function() {
    $("#outer_mouseover").bind
    ("Mouse Over Mouse Out",function(event){
    console.log(event.type," :: ",this.id);})
    $("#outer_mouseenter").bind
    ("Mouse enter Mouse leave",function(event){
    console.log(event.type," :: ",this.id);})
     });
    
  • 110

    解释得很好here

相关问题