2012-01-27 111 views
0

我要上coverImg鼠標懸停則顯示coverInfo爲什麼盒子立即消失?

的coverInfo顯示標題和圖像

的描述則coverInfo確實顯示

,但我想coverInfo留點擊時鼠標自身

但它立即消失。

那麼我錯過了什麼?

的HTML

<div class="workshop_img"> 
    <div class="coverInfo"></div> 
     <a href="#"> 
      <span class="coverImg" style="background-image:url('images/work/show1.jpg')" title="Chictopia "></span> 
     </a> 

的CSS:

.coverInfo { 
    position:absolute; 
    width: 200px; 
    height:200px; 
    background:rgba(0,0,0,0.5); 
    top:30%; 
    left:30%; 
    display:none; 
} 

看到jQuery代碼

$(function() { 

      $(".coverImg").each(function() { 
       //make the background image move a little pixels 
       $(this).css({ 
        'backgroundPosition' : "-40px 0" 
       }).mouseover(function() { 
        $(this).stop().animate({ 
         'backgroundPosition' : " -20px -60px " 
        }, { 
         duration : 90 
        }); 

        //shwo the info box 
        var content = $(this).attr("title"); 
        $("<div class='coverInfo'></div>").text(content).prependTo($(this).parent()).fadeIn("fast"); 

       }).mouseout(function() { 
        $(this).stop().animate({ 
         'backgroundPosition' : "-40px 0" 
        }, { 
         duration : 200, 
        }); 
        $(this).parent().find(".coverInfo").stop().fadeOut("fast"); 
       }) 
      }) 
     }); 

     </div> 

編輯:

我尋覓了很多,發現類似的東西,我把他們和下面給出共同解決我的問題的答案,這裏是代碼:

$(function() { 

      $(".coverImg").css({ 
       'backgroundPosition' : "-40px 0" 
      }).mouseenter(function() { 
       var box = $(this).parents(".workshop_img").find(".coverInfo"); 
       var content = $(this).attr("title"); 
       var info = box.text(content); 
        $(this).stop().animate({ 
         'backgroundPosition' : " -20px -60px " 
        },90); 
        info.show(); 

       }).mouseleave(function() { 
        var box = $(this).parents(".workshop_img").find(".coverInfo"); 
        var content = $(this).attr("title"); 
        var info = box.text(content); 
        $(this).stop().animate({ 
         'backgroundPosition' : "-40px 0" 
        },200); 
        info.stop().hide(); 
       }); 
     }); 

它剛剛乾淨,但不能正常工作。 什麼問題?

回答

1

新盒子立即顯示,因爲它最初沒有標記爲隱藏。 .fadeIn()只會淡化最初沒有顯示的內容。

你可以把它最初並不喜歡這個可視:

$("<div class='coverInfo'></div>").text(content).hide().prependTo($(this).parent()).fadeIn("fast"); 

您也可以擺脫你正在使用的.each()迭代。你不需要它。你可以使用:

$(".coverImg").css(...).mouseover(...).mouseout(...); 

你並不需要.each()可言。

我也建議你用.hover(fn1, fn2)而不是.mouseover(fn1).mouseout(fn2)

而且,看起來您正在創建一個新對象並將其插入到每個mouseover事件中,以便多個此類對象將堆積在頁面中。您應該在mouseout函數中使用.remove()對象,或者如果它存在於元素中,而不是創建更多元素,則應重新使用先前存在的元素。

有時,當您使用鼠標懸停事件並且您還在更改頁面時,對頁面的更改可能會導致元素丟失鼠標懸停,然後將更改隱藏到頁面上,然後重新開始再次。我無法確定你的情況是否發生了這種情況(我需要一個可用的例子來玩),但似乎可能。

+0

我首先使用CSS來顯示:無,這工作正常嗎? – Lien 2012-01-27 06:50:59

+0

@strangeline - 是的,它會隱藏起來。 – jfriend00 2012-01-27 06:56:45

+0

看到編輯,我接受了建議並嘗試了很多,但它仍然無法正常工作 – Lien 2012-01-27 08:30:58