How to fade changing background image

后端 未结 8 1966
旧巷少年郎
旧巷少年郎 2020-11-27 14:48

I want to fade the images when I do this code:

$(\"#large-img\").css(\'background-image\', \'url(\'+$img+\')\');

I\'ve tried putting fade i

相关标签:
8条回答
  • 2020-11-27 15:21

    Can I offer an alternative solution?

    I had this same issue, and fade didn't work because it faded the entire element, not just the background. In my case the element was body, so I only wanted to fade the background.

    An elegant way to tackle this is to class the element and use CSS3 transition for the background.

    transition: background 0.5s linear;

    When you change the background, either with toggleClass or with your code, $("#large-img").css('background-image', 'url('+$img+')'); it will fade as defined by the class.

    0 讨论(0)
  • 2020-11-27 15:21

    Building on Rampant Creative Group's solution above, I was using jQuery to change the background image of the body tag:

    e.g.

    $('body').css({'background': 'url(/wp-content/themes/opdemand/img/bg-sea.jpg) fixed', 'background-size': '100% 100%'});
    
    $('body').css({'background': 'url(/wp-content/themes/opdemand/img/bg-trees.jpg) fixed', 'background-size': '100% 100%'});
    

    I had a javascript timer that switched between the two statements.

    All I had to do to solve the issue of creating a fadeOut -> fadeIn effect was use Rampant Creative Group's suggestion and add

    transition: background 1.5s linear;
    

    to my code. Now it fades out and in beautifully.

    Thanks Rampant Creative Group's and SoupEnvy for the edit!!

    0 讨论(0)
提交回复
热议问题