如何在鼠标上更改div背景图像并添加像fadeIn这样的效果?

时间:2012-09-21 20:00:23

标签: jquery html

我看到了问题前一部分的解决方案,当我使用它时效果很好,我已将其包含在下面(感谢 rsofter ,如果你看到这个!)。我想知道必须添加哪些内容才能将fadeInfadeOut效果添加到背景图片中? 我遇到的解决方案是:

您可以使用jquery执行此操作。

您的加价:

<div id="div1"></div>
<div id="div2"></div>

你的剧本:

$("#div1").mouseover( function() {
    $("#div2").css("background-image", "url('image.png')");
});

2 个答案:

答案 0 :(得分:0)

您正在寻找的jQuery函数是animate()

$("#div1").mouseover( function() {
        $("#div2").animate({background-image: "url('image.png')"});
});

animate的作用是平滑过渡到CSS属性的地图。

这是对animate的最简单的调用,但有很多选项(请参阅链接)。您甚至可以指定动画的持续时间。

答案 1 :(得分:0)

您无法为背景图像的不透明度设置动画。这是不可能的。解决方法是在<img>

的共享parent container内放置<div id="2">

场景 - &gt;

<div id="1">
    div 1
</div>
<div id="wrapper">
    <img src="path/to/my/background/image"/>
    <div id="2">

    </div>
</div>

相对css - &gt;

#wrapper{
    position:relative;
}
#wrapper img{
    position:absolute;
        top:0;
        left:0;
    z-index:-1
}
#wrapper #div2{
    display:block;
    height: // this value should be the same as the background images size.
    width:  // this value should be the same as the background images size.
}

jQuery - &gt;

$('#div1').hover(function(){
    $('#wrapper img').fadeOut('slow', function(){
        //this is the callback function of fadeout, now change the background image URL.    
        $(this).css('background-image', 'location/to/my/new/image.ext');
        var checkForDelay = setTimeout(function(){
            //if they haven't moused out after 3 seconds, then show them the new background.
            $('#wrapper img').fadeIn('slow');
        }, 3000);
    });
}, function(){
   clearTimeout(checkForDelay);
   $('#wrapper img').fadeIn('slow');
});

jsFiddle outlining similar principals

相关问题