Events 为什么事件鼠标在javascript中触发两次

Events 为什么事件鼠标在javascript中触发两次,events,javascript-events,Events,Javascript Events,演示: js: html: 问题: 为什么事件会触发两次 为什么本机事件在chrome中触发一次,而jquery事件在chrome中触发两次 它是如何修复的 Firefox和safari两次触发了本机事件,也触发了jquery事件。 我认为这是错误的。您可以通过将事件委托给映像来解决此问题: $('.item').on('mouseenter', 'img', handler); 解决此问题的另一种方法是仅在第一次和每次调用handleRestore()时附加一次事件 var handler

演示:

js:

html:

问题:

  • 为什么事件会触发两次
  • 为什么本机事件在chrome中触发一次,而jquery事件在chrome中触发两次
  • 它是如何修复的
  • Firefox和safari两次触发了本机事件,也触发了jquery事件。
    我认为这是错误的。

    您可以通过将事件委托给映像来解决此问题:

    $('.item').on('mouseenter', 'img', handler);
    

    解决此问题的另一种方法是仅在第一次和每次调用
    handleRestore()
    时附加一次事件

    var handlerRestore = function(){
        $item.one('mouseenter', handler);
        console.log('restored');
        $item.append($img);
    };
    
    $item.one('mouseenter', handler);
    
    函数.on()可以解决您的问题。您甚至可以使用“文档”设置事件。您可以在“文档”上调用函数.on(),并设置您想要的任何事件


    下面是链接:

    我们的示例可能重复。我在“.item”上听mouseenter。你听mouseenter的“img”。我在实际代码中使用委托。这是一个简单的例子。**我们的例子不同**。我在“.item”上听mouseenter。你听mouseenter的“img”。我在实际代码中使用委托。这是一个简单的例子,当快速将鼠标悬停在div上时,img会触发两次,因为事件附加到div并传播到img。这就是为什么我认为这个问题是重复的。我不知道为什么某些浏览器会这样。但我添加了另一个解决方案来解决这个问题。事件目标是div,事件在DOM上从div传播到文档。事件冒泡未通过img。我可以使用detach event或one,但它并不优雅。我想处理这个问题。我在实际代码中使用委托。如果同时使用委托事件fider两次。
    .item {
        background: #EFEFEF;
        display: inline;
        float: left;
        height: 300px;
        margin: 0 10px 80px 0;
        position: relative;
        width: 300px;
        transition: opacity 0.6s ease;
        -moz-box-sizing: border-box;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;   
    }
    
    .item img {
        margin: auto;
        max-height: 300px;
        max-width: 300px;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
    }
    
    $('.item').on('mouseenter', 'img', handler);
    
    var handlerRestore = function(){
        $item.one('mouseenter', handler);
        console.log('restored');
        $item.append($img);
    };
    
    $item.one('mouseenter', handler);