jQuery .fadeTo() -- 淡出后淡入

EFH*_*EFH 5 html javascript css jquery

我这个项目的目标是拥有一个 div,当鼠标悬停在上面时,它会选择随机背景颜色,然后淡出。但是,我希望能够返回并再次将鼠标悬停在 div 上并重新开始该过程。到目前为止,我只设法获得随机颜色并将其淡出,但是当我将鼠标再次悬停时,什么也没有发生。尝试删除不透明度和背景类但无济于事。到目前为止,这是我的代码:

$(function() {


    var $foo = $('.foo');

    function getRandomColor() {

        $foo.removeClass('background-color');
        $foo.addClass('opacity', '1');
        var length = 6;
        var chars = '0123456789ABCDEF';
        var hex = '#';
        while(length--) hex += chars[(Math.random() * 16) | 0];
        return hex;
        }


    $foo.mouseenter(function(){

        $(this).css('background-color', getRandomColor());


        });

    $foo.mouseleave(function(){

        $(this).fadeTo( 1000, 0 );

        });


    });
Run Code Online (Sandbox Code Playgroud)

HTML - 只是一堆要测试的 div

<div class="foo box">Hello world</div>
<div class="foo box">Hello world</div>
<div class="foo box">Hello world</div>
<div class="foo box">Hello world</div>
<div class="foo box">Hello world</div>
<div class="foo box">Hello world</div>
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Ran*_*inn 3

我建议您链接 jQuery 方法,为了将不透明度设置为 0 并返回,请使用fadeOutandfadeIn以及回调来重置背景颜色。就像这样。

$(this).fadeOut(1000, function() { 
    $(this).css("background-color","transparent")
}); 
$(this).fadeIn(1000);
Run Code Online (Sandbox Code Playgroud)

具有fadeOut褪色至 0 不透明度的效果,在本例中为 1 秒。fadeIn执行相反的操作,回调会重置颜色。如果您不想重置颜色,请执行此操作。

$(this).fadeOut(1000).fadeIn(1000);
Run Code Online (Sandbox Code Playgroud)

这是一个jsFiddle。请注意,我删除了不必要的类分配,因为您无法像您尝试的那样通过类影响样式属性。