使用jQuery实现背景图片变化的动画效果

32

我终于让这个工作了,但是我想知道如何使用JQuery的animate函数在主页上悬停列表项时使背景图片更好地淡入:

http://www.thebalancedbody.ca/

到目前为止,需要实现的代码是:

$("ul#frontpage li#277 a").hover(
    function() {
        $('#homepage_container').css('background-image', 'url(http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/nutrition_background.jpg)');
    },
    function() {
        $('#homepage_container').css('background-image', 'url(http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/default_background.jpg)');
    }
);

$("ul#frontpage li#297 a").hover(
    function() {
        $('#homepage_container').css('background-image', 'url(http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/vibration_training.jpg)');
    },
    function() {
        $('#homepage_container').css('background-image', 'url(http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/default_background.jpg)');
    }
);

请问我该如何添加ANIMATE函数到这里呢?谢谢!

谢谢。

Jonathan


这是解决方案的链接解决方案链接-设置CSS淡入和延迟 - Zee
9个回答

32

我认为使用jQuery的animate函数无法实现此类淡入淡出效果,因为背景图像没有必要的CSS属性来实现。jQuery只能利用浏览器所支持的功能。(当然,如果我有错,请jQuery专家纠正我。)

我想你需要通过不使用真正的background-image,而是使用包含图像的div元素,通过position: absolute(或fixed)和z-index进行堆叠定位。然后您可以对这些div进行动画处理。


6
@Jonathan - 是的,通过动画化 background-position 实现,就像这样:http://snook.ca/technical/jquery-bg/ - Nick Craver
那个链接真不错。我有一段时间在使用那个插件,现在我可以为背景图像增加动画效果了,简直太棒了!你可以在这里看到我的最新背景动画:http://mashinaizec.com/ ,我正在给这张图片添加动效:http://mashinaizec.com/css/images/nav_background.png - Gavrisimo
我认为我已经正确地完成了它,但无法使其工作。$("ul#frontpage li#277 a").hover( function () { $('#homepage_container').stop().animate({backgroundPosition:"(0 -1200)"}, {duration:500}); },function () { $('#homepage_container').stop().animate({backgroundPosition:"(0 0)"}, {duration:500});; } ); - Jonathan Lyon
谢谢Pekka - 可能是这个问题,或者没有正确链接到bgpos.js文件 - 无论如何,现在它可以工作了http://www.thebalancedbody.ca/ - 然而,我更希望它可以淡入每张图片,而不是滑动。有什么想法吗? - Jonathan Lyon
我刚刚想通了,看看我的答案。哈哈,我没有意识到,但这正是你在帖子中所说的。 - Milimetric
显示剩余7条评论

18

在上面XGreen的方法基础上进行一些调整,你可以拥有一个动画循环的背景。例如,请参见这里:

http://jsfiddle.net/srd76/36/

$(document).ready(function(){

var images = Array("http://placekitten.com/500/200",
               "http://placekitten.com/499/200",
               "http://placekitten.com/501/200",
               "http://placekitten.com/500/199");
var currimg = 0;


function loadimg(){

   $('#background').animate({ opacity: 1 }, 500,function(){

        //finished animating, minifade out and fade new back in           
        $('#background').animate({ opacity: 0.7 }, 100,function(){

            currimg++;

            if(currimg > images.length-1){

                currimg=0;

            }

            var newimage = images[currimg];

            //swap out bg src                
            $('#background').css("background-image", "url("+newimage+")"); 

            //animate fully back in
            $('#background').animate({ opacity: 1 }, 400,function(){

                //set timer for next
                setTimeout(loadimg,5000);

            });

        });

    });

  }
  setTimeout(loadimg,5000);

});

15
<style type="text/css">
    #homepage_outter { position:relative; width:100%; height:100%;}
    #homepage_inner { position:absolute; top:0; left:0; z-index:10; width:100%; height:100%;}
    #homepage_underlay { position:absolute; top:0; left:0; z-index:9; width:800px; height:500px; display:none;}
</style>

<script type="text/javascript">
    $(function () {

        $('a').hover(function () {

            $('#homepage_underlay').fadeOut('slow', function () {

                $('#homepage_underlay').css({ 'background-image': 'url("http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/nutrition_background.jpg")' });

                $('#homepage_underlay').fadeIn('slow');
            });

        }, function () {

            $('#homepage_underlay').fadeOut('slow', function () {

                $('#homepage_underlay').css({ 'background-image': 'url("http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/default_background.jpg")' });

                $('#homepage_underlay').fadeIn('slow');
            });


        });

    });

</script>


<body>
<div id="homepage_outter">
    <div id="homepage_inner">
        <a href="#" id="run">run</a>
    </div>
    <div id="homepage_underlay"></div>
</div>


11

我也遇到了同样的问题,在大量的研究和谷歌搜索后,我找到了以下解决方案,对我来说这个方案是最好的!在实践中进行了大量的尝试和错误。

--- 已解决/解决方案 ---

JS

$(document).ready(function() {
            $("header").delay(5000).queue(function(){
                $(this).css({"background-image":"url(<?php bloginfo('template_url') ?>/img/header-boy-hover.jpg)"});
            });
        });

CSS

header {
    -webkit-transition:all 1s ease-in;
    -moz-transition:all 1s ease-in;
    -o-transition:all 1s ease-in;
    -ms-transition:all 1s ease-in;
    transition:all 1s ease-in;
}

3

这可以通过jquery和css完成。我以一种适用于动态情况的方式完成了它,您只需在jquery中更改background-image,它将完成所有操作,还可以在css中更改时间。

代码片段: https://jsfiddle.net/Naderial/zohfvqz7/

Html:

<div class="test">

CSS:

.test {
  /* as default, we set a background-image , but it is not nessesary */
  background-image: url(http://lorempixel.com/400/200);
  width: 200px;
  height: 200px;
  /* we set transition to 'all' properies - but you can use it just for background image either - by default the time is set to 1 second, you can change it yourself*/
  transition: linear all 1s;
  /* if you don't use delay , background will disapear and transition will start from a white background - you have to set the transition-delay the same as transition time OR more , so there won't be any problems */
  -webkit-transition-delay: 1s;/* Safari */
  transition-delay: 1s;
}

JS:

$('.test').click(function() {
  //you can use all properties : background-color  - background-image ...
  $(this).css({
    'background-image': 'url(http://lorempixel.com/400/200)'
  });
});

2
看看这个来自OvalPixels的jQuery插件,它可能会有用。

1
最简单的解决方案是用 div 包装元素。这个包装 div 将有隐藏的背景图片,在内部元素淡出时会显示出来。
以下是一些示例 JavaScript:
$('#wrapper').hover(function(event){
    $('#inner').fadeOut(300);
}, function(event){
    $('#inner').fadeIn(300);
});

而且这是与之相关的HTML:

and here's the html to go along with it:

<div id="wrapper"><div id="inner">Your inner text</div></div>

0
$('.clickable').hover(function(){
      $('.selector').stop(true,true).fadeTo( 400 , 0.0, function() {
        $('.selector').css('background-image',"url('assets/img/pic2.jpg')");
        });
    $('.selector').fadeTo( 400 , 1);
},
function(){
      $('.selector').stop(false,true).fadeTo( 400 , 0.0, function() {
        $('.selector').css('background-image',"url('assets/img/pic.jpg')");
        });
    $('.selector').fadeTo( 400 , 1);
}

);

0

好的,我想出来了,这个很简单,只需要用一点 HTML 技巧:

http://jsfiddle.net/kRjrn/8/

HTML

<body>
    <div id="background">.
    </div>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>    
</body>​

JavaScript

$(document).ready(function(){
    $('#background').animate({ opacity: 1 }, 3000);
});​

CSS

#background {
    background-image: url("http://media.noupe.com//uploads/2009/10/wallpaper-pattern.jpg");
    opacity: 0;
    margin: 0;
    padding: 0;
    z-index: -1;
    position: absolute;
    width: 100%;
    height: 100%;
}​

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接