¿Puedo fade en una imagen de fondo (CSS: background-image) con jQuery?


Tengo un elemento div con texto y una imagen de fondo, que se establece a través de la propiedad CSS background-image. ¿Es posible desvanecerse en la imagen de fondo a través de jQuery?

div {
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  background-image: url(http://upload.wikimedia.org/wikipedia/commons/8/84/Konqi_svg.svg);
  border: 1px solid #666;
  height: 10em;
}
<div>Text</div>

EDITAR

He hecho un violín ejemplificando mi escenario. Básicamente, esto configura un background-image inicial y un transition, y cambia el background-image con jQuery. En mi prueba no hay transición animada entre los dos images.

EDIT2

Mi violín revisado funciona!

Author: Mosh Feu, 2011-09-06

9 answers

Probablemente no con jquery pero puedes con transiciones css3 ver este ejemplo:

Http://css3.bradshawenterprises.com/cfimg /

Ver También esta respuesta

CSS3 Fade Effect

 19
Author: Richard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:01

He estado buscando durante siglos y finalmente puse todo junto para encontrar mi solución. La gente dice, no se puede fade-in / - out el background-image-id del html-background. Eso es definitivamente mal como se puede averiguar mediante la implementación de la demostración mencionada a continuación

CSS:

html, body

height: 100%;   /* ges Hoehe der Seite -> weitere Hoehenangaben werden relativ hierzu ausgewertet */
overflow: hidden;   /*  hide scrollbars */
opacity: 1.0;
-webkit-transition: background 1.5s linear;
-moz-transition: background 1.5s linear;
-o-transition: background 1.5s linear;
-ms-transition: background 1.5s linear;
transition: background 1.5s linear;

Cambiar la imagen de fondo del cuerpo ahora se puede hacer fácilmente usando JavaScript:

switch (dummy)

case 1:

$(document.body).css({"background-image": "url("+URL_of_pic_One+")"});
waitAWhile();

case 2:
$(document.body).css({"background-image": "url("+URL_of_pic_Two+")"});
waitAWhile();
 29
Author: user2947794,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-02 13:38:48

Puede dar el valor de opacidad como

div {opacity: 0.4;}

Para IE, puede especificar como

div { filter:alpha(opacity=10));}

Baje el valor - Aumente la transparencia.

 5
Author: Dhepthi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-21 16:41:38

No es posible hacerlo así, pero puede superponer un div opaco entre el div con la imagen de fondo y el texto y desvanecerlo, dando la apariencia de que el fondo se está desvaneciendo.

 4
Author: thwd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-06 12:03:06

Esto es lo que funcionó para mi, y su css puro


Css

html {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
  }

  body {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
  }

  #bg {
    width: 100%;
    height: 100%;
    background: url('/image.jpg/') no-repeat center center fixed;

    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

    -webkit-animation: myfirst 5s ; /* Chrome, Safari, Opera */
    animation: myfirst 5s ;
  }

  /* Chrome, Safari, Opera */
  @-webkit-keyframes myfirst {
    from {opacity: 0.2;}
    to {opacity: 1;}
  }

  /* Standard syntax */
  @keyframes myfirst {
    from {opacity: 0.2;}
    to {opacity: 1;}
  }

Html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
  <div id="bg">
    <!-- content here -->
  </div> <!-- end bg -->
</body>
</html>
 4
Author: tomter2014,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-08 13:42:11

Con el navegador moderno prefiero un enfoque mucho más ligero con un poco de Js y CSS3...

transition: background 300ms ease-in 200ms;

Mira esta demo:

Http://codepen.io/nicolasbonnici/pen/gPVNbr

 2
Author: Nicolas Bonnici,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-31 14:20:11

Puedes difuminar tu imagen de fondo de varias maneras desde Firefox 4 ...

Tu CSS:

.box {
    background: #CCCCCC;
    -webkit-transition: background 0.5s linear;
    -moz-transition: background 0.5s linear;
    -o-transition: background 0.5s linear;
    transition: background 0.5s linear;
    }
.box:hover {
    background: url(path/to/file.png) no-repeat #CCCCCC;
    }

Su XHTML:

<div class="box">
    Some Text …
</div>

Y eso es todo.

 1
Author: yokmp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-16 22:03:42

Jquery:

 $("div").fadeTo(1000 , 1);

Css

    div {
     background: url("../images/example.jpg") no-repeat center; 
    opacity:0;
    Height:100%;
    }

Html

<div></div>
 1
Author: zyad osseyran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-23 16:58:44

Sé que llego tarde, pero encontré una manera de usar jquery que funciona en todos los navegadores(lo probé en chrome, firefox e Ie 9)y los elementos de avance siempre se muestran en lugar de la propiedad de transición css3.

Crear 2 envoltura absoluta y usando z-index.

Primero establezca los elementos que tienen que estar en el suelo delantero con el valor de propiedad z-index más alto, y los otros elementos (todos incluidos en el cuerpo, por lo que: cuerpo{}) con un valor de propiedad z-index más bajo que el suelo delantero element'one, al menos de 2 número menor.

Parte HTML:

         <div class="wrapper" id="wrapper1"></div>
         <div class="wrapper" id="wrapper2"></div>

Parte CSS:

        .fore-groundElements{              //select all fore-ground elements
                  z-index:0;               //>=0
        }
       .wrapper{
                  background-size: cover;
                  width:100%;
                  height:100%;
                  background-size: 100% 100%;
                  position:absolute;
         }

        #wrapper1{
               z-index:-1; 
        }


        #wrapper2{
                 z-index:-2;
         }
         body{

              height:100%;
              width:100%;
              margin:0px;   
              display:cover;
              z-index:-3                          //<=-3
         }

Que el de javascript / jquery:

Necesitaba cambiar la imagen de fondo cada tres segundos, así que usé un tiempo de espera establecido.

Este es el código:

  $(document).ready(main);

  var main = function(){

             var imgPath=[imagesPath1,..,...];                 // the array in which store the image paths

             var newWrapper;                     // the wrapper to display 
             var currentWrapper;                 //the current displayed wrapper which has to be faded
             var l=2;                             // the next image index  to be displayed, it is set to 2 because the first two position of the array(first two images) start already setted up
             var imgNumber= imgPath.length;        //to know when the images are over and restart the carousel
             var currentImg;                       //the next image path to be displayed


             $('#wrapper1').css("background-image", 'url'+imgPath[0]);         //pre set the first wrapper background images
             $('#wrapper2').css("background-image", 'url'+imgPath[1]);          //pre set the first wrapper background images   

             setInterval(myfunction,3000);                //refresh the background image every three seconds

             function myfunction(){
                    if(l===imgNumber-1){               //restart the carousel if every single image has already been displayed                  
                         l=0;
                     };

             if(l%2==0||l%2==2){                    //set the wrapper that will be displaied after the fadeOut callback function
                  currentWrapper='#wrapper1';         
                  newWrapper='#wrapper2';
             }else{
                  currentWrapper='#wrapper2';
                  newWrapper='#wrapper1';
             };
             currentImg=imgPath[l];
            $(currentWrapper).fadeOut(1000,function(){               //fade out the current wrapper, so now the back-ground wrapper is fully displayed
                  $(newWrapper).css("z-index", "-1");                //move the shown wrapper in the fore-ground
                  $(currentWrapper).css("z-index","-2");             //move the hidden wrapper in the back ground
                  $(currentWrapper).css("background-image",'url'+currentImg);                   // sets up the next image that is now shown in the actually hidden background wrapper
                  $(currentWrapper).show();          //shows the background wrapper, which is not visible yet, and it will be shown the next time the setInterval event will be triggered
                  l++;                         //set the next image index that will be set the next time the setInterval event will be triggered 
             });


         };                   //end of myFunction
  }                          //end of main

Espero que mi respuesta sea clara,si necesita más explicación coméntela.

Lo siento por mi inglés:)

 0
Author: Muccagelato,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-02 12:33:45