jQuery:淡出当前的不透明度

时间:2010-11-16 14:22:25

标签: jquery animation fadein fadeout

我在mouseOver上将对象从0%淡化为100%,在mouseOut上淡出0%。

当我快速mouseInmouseOut时,效果会“跳跃”,因为mouseOut从100%逐渐消失 - 因为我快速mouseIn并且mouseOut,淡入不会一直消失到100%。也许它只会消退到25%或10%。

我的问题是: 如何才能使淡出效果仅从特定百分比中消失?

如果fadeIn只有20,则fadeOut应该是fadeOut从20开始。

4 个答案:

答案 0 :(得分:1)

您可以尝试:

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

...而不是fadeOut()。

答案 1 :(得分:1)

我不确定你当前的代码是什么样的,但是你想要使用jQuery .animate()函数:

http://api.jquery.com/animate/

以下是一个例子:

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

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

答案 2 :(得分: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

答案 3 :(得分: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/

相关问题