2013-02-14 67 views
0

我在我的頁面上有某些項目。當某人懸停物品時,我想在該物品上覆蓋一個div。如果我在不使用$(this)的情況下使用該功能,則此功能正常,但它覆蓋了所有項目。我想只覆蓋那個時候我徘徊的物品。這不是在jQuery功能工作

我的代碼:

的jQuery:

<script> 
    $(document).on("mouseenter", ".item" , function() { 
    $(this).('.item-overlay').stop().fadeTo(250, 1); 
    }); 
    $(document).on("mouseleave", ".item" , function() { 
    $(this).('.item-overlay').stop().fadeTo(250, 0); 
    }); 
</script> 

HTML:

<div class="item"> 
    <a href="#"><img src="<?=$row['item_pic']?>" class="item-img"></a> 
    <div class="item-overlay" style="background:#999; display: none; position:absolute; top:0px; left: 0px; width:400px; height:200px; z-index:900;">test</div> 
</div> 
+0

$(本)參考文檔我認爲.. – 2013-02-14 16:51:48

回答

1

此:

$(this).('.item-overlay') 

是無效的,也許應該是:

$(this).find('.item-overlay') 

總數:

<script type="text/javascript"> 
$(function() { 
    $(document).on({ 
     mouseenter: function() { 
      $(this).find('.item-overlay').stop().fadeTo(250, 1); 
     },  
     mouseleave: function() { 
      $(this).find('.item-overlay').stop().fadeTo(250, 0); 
     } 
    }, '.item'); 
}); 
</script> 

只是爲了好玩,這裏有一個較短的版本:

$(function() { 
    $(this).on('mouseenter mouseleave', '.item', function(e) { 
    $(this).find('.item-overlay')[e.type=='mouseenter'?'fadeIn':'fadeOut'](250); 
    }); 
}); 
+0

要評論此解決方案,您需要將您的代碼或者使用這種類型的解決方案,它是一種簡短形式的jquerys ready函數,可在http://api.jquery.com/ready/找到,它在執行之前等待頁面加載。 – fanfavorite 2013-02-14 16:53:13

+0

@fanfavorite - 您沒有注意到DOM就緒功能嗎?它一直在那裏,並且完全符合你的評論? – adeneo 2013-02-14 16:54:30

+0

我知道,我只是用解決方案向用戶解釋更多。 :) – fanfavorite 2013-02-14 16:55:31

0
$(function() { 
$(document).on("mouseenter", ".item" , function() { 
    $(this).children('.item-overlay').stop().fadeTo(250, 1); 
}); 

$(document).on("mouseleave", ".item" , function() { 
    $(this).children('.item-overlay').stop().fadeTo(250, 0); 
}); 

});

需要的 「孩子」

0

試試這個腳本:

$(document).on("mouseenter", ".item" , function() { 
    $('.item-overlay').stop().fadeTo(250, 1); 
}); 

$(document).on("mouseleave", ".item" , function() { 
    $('.item-overlay').stop().fadeTo(250, 0); 
}); 

我只是刪除了$(本)

希望它可以幫助

+0

此代碼將使用類項目疊加來淡出所有項目,而不是與項目相關聯的元素。 – 2013-02-14 17:03:14

+0

檢查出這個小提琴:http://jsfiddle.net/mareebsiddiqui/tdf6g/ 盒僅在未來由於定位的頂部! – 2013-02-14 17:15:19

+0

添加多個.item,代碼失敗。 – 2013-02-14 17:21:23