2011-05-11 117 views
4

我有jQuery的褪色打算在這裏:http://dougie.thewestharbour.com/jQuery的褪色閃爍

當你將鼠標懸停在。主要的覆蓋DIV我想它淡出那麼當你把你的鼠標關閉它,我想它想淡入。

但是,你可以看到它現在只是閃爍。我猜這是因爲div消失了,所以它在淡出時被當作鼠標使用,但我不知道如何去解決它。

這裏是我的javascript:

$(document).ready(function() { 


    $('.main-overlay').hover(

     //Mouseover, fadeIn the hidden hover class 
     function() { 

      $(this).fadeOut('1000'); 

     }, 

     //Mouseout, fadeOut the hover class 
     function() { 

      $(this).fadeIn('1000'); 

    }).click (function() { 

     //Add selected class if user clicked on it 
     $(this).addClass('selected'); 

    }); 

}); 

這裏是一個項目的覆蓋DIV連接到:

<li><div class="main-overlay"></div><span class="caption">The store front</span><img src="http://dougie.thewestharbour.com/wp-content/uploads/store-front.jpg" alt="store front" title="store-front" width="730" height="360" class="alignnone size-full wp-image-98" /></li> 

感謝,

韋德

回答

11

這是因爲fadeOut在它的末尾有一個display:none,所以當你在fadeOut完成後移動你的鼠標時,它將觸發unhover功能。相反,只是animateopacity

$('.main-overlay').hover(function() { 
    $(this).animate({opacity: 0}, 1000); 
}, function() { 
    $(this).animate({opacity: 1}, 1000); 
}) 

Example →

+0

感謝了很多,知道了吧! – 2011-05-11 17:42:08

+0

我很喜歡這個解決方案!但是,這個元素不會保持可見,可能覆蓋了它不應該覆蓋的背景中的東西嗎? – SquareCat 2013-03-22 07:49:53

1

至於其他的答案中提到,在年底fadeOutdisplay:none,所以該元素不再影響頁面的佈局。只是動畫不透明度的建議是正確的,但已經有這樣做,fadeTo功能,這比自己寫的動畫清潔一丁點兒:

$('.main-overlay').hover(
    //Mouseover, fadeIn the hidden hover class 
    function() { 
     $(this).fadeTo(0,1000); 
    }, 
    //Mouseout, fadeOut the hover class 
    function() { 
     $(this).fadeTo(1,1000); 
}) 
+2

雖然這個解決方案有效(並且肯定比使用'animate'更清晰),fadeTo方法實際上是'.fadeTo(duration,opacity [,complete])''。 所以上面應該是FadeIn:'fadeTo(1000,0)'和FadeOut:'fadeTo(1000,1)'。好的解決方案。 – 2016-06-07 20:50:19