繁体   English   中英

jQuery mouseenter不适用于特定的div

[英]jquery mouseenter is not working for specific div

单击此处查看演示。

这是代码

jQuery(document).ready(function($) {
  $(".works").mouseenter(function(e) {

        $( ".img_details" ).stop().animate({ 'bottom':'5%', 'opacity':'1'},500);
        e.preventDefault();
    });

    $( ".works").mouseleave(function(e) {

        $( ".img_details" ).stop().animate({ 'bottom':'100%', 'opacity':'0'},500);
        e.preventDefault();
    });

})(jQuery);

有两个div,其类名称为“ works”,其中包含一个div,其名称为“ img_details”。 如果鼠标指针进入第一个div,“ img_details”也将同时加载到两个div中。 我想加载一次特定的div。 我错过了什么?

你应该使用thisthis将指向当前对象,这将是目前徘徊.works ,然后你发现的具体.img_detailsthis只有动画效果的元素。

jQuery(document).ready(function($) {
  $(".works").mouseenter(function(e) {

        $(this).find( ".img_details" ).stop().animate({ 'bottom':'5%', 'opacity':'1'},500);
        e.preventDefault();
    });

    $( ".works").mouseleave(function(e) {

        $(this).find( ".img_details" ).stop().animate({ 'bottom':'100%', 'opacity':'0'},500);
        e.preventDefault();
    });

})(jQuery);

柱塞

请使用上下文this

jQuery(document).ready(function($) {
  $(".works").mouseenter(function(e) {
    $(this).find(".img_details").stop().animate({
      'bottom': '5%',
      'opacity': '1'
    }, 500);
    e.preventDefault();
  });
  $(".works").mouseleave(function(e) {
    $(this).find(".img_details").stop().animate({
      'bottom': '100%',
      'opacity': '0'
    }, 500);
    e.preventDefault();
  });
})(jQuery);

原因:当您再次提供.works时,它将以文档中的每个.works为目标。 但是,当您在回调函数中提供this 选项时 ,它仅引用发生mouseenter的当前<div> 这是所有jQuery新手都犯的一个普遍错误。 :)

输出: http : //plnkr.co/edit/bKc00tEebxs9TAONBid4?p=preview

( ".img_details" )将选择所有具有img_details类的div 您应该在works下找到img_details并对其进行动画处理,如下所示。

$(".works").mouseenter(function(e) {    
    $(this).find( ".img_details" ).stop().animate({ 'bottom':'5%', 'opacity':'1'},500);
    e.preventDefault();
});

$( ".works").mouseleave(function(e) {
    $(this).find( ".img_details" ).stop().animate({ 'bottom':'100%', 'opacity':'0'},500);
    e.preventDefault();
});

柱塞: http ://plnkr.co/edit/HO7PuyfFwNZj4rpWJwU4?p = preview

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM