因此,在看到所有组件都受mouseenter()影响后,我添加了.each(),但是因为这是一个图片库...我只希望一个组件受到影响。

$(document).ready(function(){
    $(".component").each(function(){
        $(this).mouseenter(function(){
            $(".primary").css({"margin-right":"0", "transition":"1s"});
            $(".secondary").css({"margin-left":"0", "transition":"1s"});
        });

        $(this).mouseleave(function(){
            $(".primary").css({"margin-right":"30px", "transition":"1s"});
            $(".secondary").css({"margin-left":"30px", "transition":"1s"});
        });
    });
});

最佳答案

在JavaScript中使用事件传播机制

var theParent = document.querySelector("#idOfParent");
theParent.addEventListener("mouseenter", doYourStuffforMouseEnterEvent,false);
theParent.addEventListener("mouseleave", doYourStuffforMouseLeaveEvent,false);

function doYourStuffforMouseEnterEvent(e) {
  if (e.target !== e.currentTarget) {
     var Item = e.target.id;
     alert("This item is the current hover item " + Item );
     $(".primary").css({"margin-right":"0", "transition":"1s"});
     $(".secondary").css({"margin-left":"0", "transition":"1s"});
   });
  }
 e.stopPropagation();
}

function doYourStuffforMouseLeaveEvent(e) {
  if (e.target !== e.currentTarget) {
     var Item = e.target.id;
     alert("This item is the current hover item " + Item );
     $(".primary").css({"margin-right":"30px", "transition":"1s"});
     $(".secondary").css({"margin-left":"30px", "transition":"1s"});
    });
  }
 e.stopPropagation();
}

10-04 16:07
查看更多