How to fade changing background image

后端 未结 8 1942
旧巷少年郎
旧巷少年郎 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 14:56

    This was the only reasonable thing I found to fade a background image.

    <div id="foo">
      <!-- some content here -->
    </div>
    

    Your CSS; now enhanced with CSS3 transition.

    #foo {
      background-image: url(a.jpg);
      transition: background 1s linear;
    }
    

    Now swap out the background

    document.getElementById("foo").style.backgroundImage = "url(b.jpg)";
    

    Voilà, it fades!


    Obvious disclaimer: if your browser doesn't support the CSS3 transition property, this won't work. In which case, the image will change without a transition. Given <1% of your users' browser don't support CSS3, that's probably fine. Don't kid yourself, it's fine.

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

    If your trying to fade the backgound image but leave the foreground text/images you could use css to separate the background image into a new div and position it over the div containing the text/images then fade the background div.

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

    Someone pointed me to this thread because I had this same issue but it didn't work for me. After hours of searching I found a solution using this - https://github.com/rewish/jquery-bgswitcher#readme

    It has a few other options other than fade too.

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

    Opacity serves your purpose?

    If so, try this:

    $('#elem').css('opacity','0.3')
    
    0 讨论(0)
  • 2020-11-27 15:20

    This may help

    HTML

    <div id="textcontainer">        
        <span id="sometext">This is some information </span>
        <div id="container">
    
        </div>
    </div>
    

    CSS

    #textcontainer{
        position:relative;
        border:1px solid #000;
        width :300px;
        height:300px;
    }
    #container{
        background-image :url("http://dcooper.org/gallery/cf_appicon.jpg");
        width :100%;
        height:100%;
    }
    #sometext{
        position:absolute;
        top:50%;
        left:50%;
    }
    

    Js

    $('#container').css('opacity','.1');
    
    0 讨论(0)
  • 2020-11-27 15:21

    This is probably what you wanted:

    $('#elem').fadeTo('slow', 0.3, function()
    {
        $(this).css('background-image', 'url(' + $img + ')');
    }).fadeTo('slow', 1);
    

    With a 1 second delay:

    $('#elem').fadeTo('slow', 0.3, function()
    {
        $(this).css('background-image', 'url(' + $img + ')');
    }).delay(1000).fadeTo('slow', 1);
    
    0 讨论(0)
提交回复
热议问题