如何在Jquery中使用.css更改背景图像时添加淡入淡出效果

时间:2011-02-20 20:59:30

标签: jquery fadein css fadeto

嘿伙计们,我试图在Jquery中使用.css更改我的背景图像时添加一个fadein效果 我真的不太了解java,希望有人可以帮助我!

更改css背景图片的代码非常简单:

$(document).ready(function(){
$("#button01").click(function () {
      $("#content_wrapper").css({backgroundImage : 'url(image/staff/shinji.jpg)' } );
        });
    }); 

它就像一个图像库,我只是在css背景图像中显示它 一切正常,但我想知道是否可以添加淡入或淡入效果。

2 个答案:

答案 0 :(得分:1)

您不能将一个图像淡化为另一个图像,只能将实体背景颜色等属性淡化。

你可以做的是淡化包含图像的元素的不透明度。

使用这种方法,为了达到你想要的效果,你必须做的就是让2张图像一个在另一个上面。

然后你可以在淡出另一个的同时淡出一个。

类似于:

// write a little function to do a toggling fade
jQuery.fn.fadeToggle = function(speed, easing, callback) { 
   return this.animate({opacity: 'toggle'}, speed, easing, callback); 
};

// make sure one layer is marked as active and shown and the other is hidden
$("#layer1").show();
$("#layer2").addClass('inactive').hide();

// then you can do this:
$("#button01").click(function () {
    $("#layer1").fadeToggle('slow').toggleClass('inactive');
    $("#layer2").fadeToggle('slow').toggleClass('inactive');
    // then set the new background image for the hidden layer
    $(".inactive").css({backgroundImage : 'url(image/staff/shinji.jpg)' } );
};

可能不是一种美好的方式,但我认为它应该有用。

答案 1 :(得分:0)

对于淡入淡出效果,您需要同时在一定程度上显示两个图像。我建议你使用2层。底部将始终包含您想要淡出的图像。顶部的图层将包含将变为透明的图像。

您的容器内部的任何内容都将无法使用淡化背景,或淡化效果也会影响内容。

然后使用带有效果的jQuery,执行以下操作:

$('#element').fadeOut('slow', function() {
    // Animation complete.
});
相关问题