javascript 如何在 jquery 中为淡入淡出和淡出背景图像设置动画?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17714954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:18:48  来源:igfitidea点击:

How I can animate fadin and fadeout background image in jquery?

javascriptjquery

提问by user2560165

I have a background-image that must be animated through fadein and fadeout effect on hover event. How I can do that?

我有一个背景图像,必须通过悬停事件的淡入和淡出效果进行动画处理。我怎么能做到这一点?

回答by Praveen

HTML:

HTML:

<div></div>

CSS:

CSS:

div {
    width:200px;
    height:200px;
    background-image:url(http://dummyimage.com/100x100/000/fff);
}

jQuery:

jQuery:

$('div').hover(function () {
    $(this).stop().fadeOut("1000", function () {
        $(this).css("background", "url('http://dummyimage.com/100x100/000/ff0000')").fadeIn(1000);
    });
}, function () {
    $(this).stop().fadeOut("1000", function () {
        $(this).css("background", "url('http://dummyimage.com/100x100/000/fff')").fadeIn(1000);
    });
});

Check this fiddle1.

检查这个fiddle1

Incase if you wish to it using CSS3 transitionthen,

如果你想使用CSS3 过渡,那么,

change the CSSlike this

改成CSS这样

div {
    height: 200px;
    width: 200px;
    color: black;
    background-image:url(http://dummyimage.com/100x100/000/fff);
    transition: background-image 1s linear;
    -moz-transition: background-image 1s linear;
    -webkit-transition: background-image 1s linear;
    -ms-transition: background-image 1s linear;
}
div:hover {
    background-image:url(http://dummyimage.com/100x100/000/ff0000);
}

Fiddle2

小提琴2