2010-11-16 59 views
0

我在mouseOver上將對象從0%褪色到100%,並在mouseOut上淡出爲0%。jQuery:從當前不透明度中淡出

當我做一個快速mouseInmouseOut,效果「跳躍」,因爲mouseOut從100%淡出 - 因爲我做一個快速mouseInmouseOut,淡入不會一路褪色至100% 。也許它只會減少到25%或10%。

我的問題是: 如何讓淡出僅從特定百分比中消失?

如果fadeIn只到達20時,fadeOut應該fadeOut從20

回答

1

你可以嘗試這樣做:

$('#element').animate({opacity:0}); 

,而不是淡出...()。

+1

如果這不起作用,你可以嘗試'.stop()'並再次啓動'.fadeOut()'。 – Fabian 2010-11-16 14:29:01

1

我不知道你當前的代碼是什麼樣子,但你需要使用jQuery的.animate()函數:

下面是一個例子:

$('#object').mouseover(function() { 
    $(this).animate({ 
    opacity: 1, 
    }, 1000, function() { 
    //completion code? 
    }); 
}); 

$('#object').mouseout(function() { 
    $(this).animate({ 
    opacity: 0, 
    }, 1000, function() { 
    //completion code?? 
    }); 
}); 
0

我曾經有過同樣的問題。你不能真正使用jQuery的動畫函數,因爲它總是想完成動畫。所以我寫了我自己的函數吧..希望這會有所幫助(我也沒想到分享這一天,所以它已經寫入要適合我如何使用它):

//Custom fade effects. 
//Similar to jQuery's fadeIn & fadeOut 
//Except that it doesn't queue animations, and can cut the animation short at anytime 
//Highly useful for quickly hovering over elements and desiring the fade effects to be cut on hover in/out. 

function fade(elem, interval) 
{ 
    if(!(elem instanceof $)) { 
     elem = $(elem); 
    } 

    if(elem.is(':not(:visible)')) { 
     elem.css('opacity', '0').show(); 
    } 

    elem.css('opacity', function() { 
      var current = $(this).data('fadeLevel') || 0; 

      //normalize - accounts for tiny descrepancies in parsing 
      if(current < 0) { current = 0; } 
      if(current > 1) { current = 1; } 

      $(this).data('fadeLevel', current + interval) 

      return $(this).data('fadeLevel'); 
     }); 

    if(elem.data('fadeLevel') < 0 || elem.data('fadeLevel') > 1) { 
     clearTimeout(elem.data('fadeTimer')); 
    } 
} 

function fadeIn(elem) { fadeTo(elem, 0.04, 0); } 
function fadeOut(elem) { fadeTo(elem, -0.04, 1); } 
function fadeTo(elem, interval, level) { 
    if(!$(elem).data('itemOpen')) { 
     clearTimeout($(elem).data('fadeTimer')); 
     $(elem).data('fadeLevel', level).data('fadeTimer', setInterval(function() { fade(elem, interval) }, 30)); 
    } 
} 

例子

http://jsfiddle.net/3AxHb/

1

使用jQuery's .fadeTo() method它可以讓你設定的目標不透明度。

$('selector').fadeTo('slow', 1); 
$('selector').fadeTo('slow', 0); 

第一個參數是速度,第二個參數是不透明度。


如果您使用.hover()你可以做這樣的:

例子:http://jsfiddle.net/ecUdS/

$('selector').hover(function(evt) { 
    $(this).stop().fadeTo('slow', evt.type === 'mouseenter'); 
}); 

uses .stop(),如果它在運行停止動畫。

然後because .hover()將火爲mouseentermouseleave兩個,我加了一個測試,如果它是一個mouseenter,它會發出true(這將等同於1)。否則,它會發送false0

相關問題