2015-12-19 31 views
0

Click here to view the demo.的jQuery的mouseenter工作不針對特定的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與類名「作品」,它認爲具有類名「img_details」一個DIV 。如果鼠標指針進入第一個div「img_details」也加載到兩個div。我想加載一次特定的div。我錯過了什麼?

+3

在這兩種處理程序使用'$( 「img_details。」,這一點).sto ...' – Tushar

回答

3

你應該使用thisthis將指向當前對象,這將是目前徘徊.works,然後你發現裏面this具體.img_details只有動畫效果的元素。

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); 

Plunker

2

請使用上下文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時,它僅指當前<div>,其中mouseenter發生。這是所有jQuery新手所犯的常見錯誤。 :)

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

2

(".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(); 
}); 

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