Pregunta

Tengo una página web que utiliza una imagen grande para su fondo. Tenía la esperanza de usar jQuery para cargar la imagen una vez que se haya descargado (básicamente la forma en que bing.com carga su imagen de fondo). ¿Es esto posible con jQuery? Si es así, ¿hay un plugin que usted recomendaría?

¿Fue útil?

Solución

Esta href="http://jqueryfordesigners.com/image-loading/" artículo puede ser útil. Copiar desde allí:

HTML

<div id="loader" class="loading"></div>

CSS

DIV#loader {
  border: 1px solid #ccc;
  width: 500px;
  height: 500px;
}

/** 
 * While we're having the loading class set.
 * Removig it, will remove the loading message
 */
DIV#loader.loading {
  background: url(images/spinner.gif) no-repeat center center;
}

Javascript

// when the DOM is ready
$(function () {
  var img = new Image();

  // wrap our new image in jQuery, then:
  $(img)
    // once the image has loaded, execute this code
    .load(function () {
      // set the image hidden by default    
      $(this).hide();

      // with the holding div #loader, apply:
      $('#loader')
        // remove the loading class (so no background spinner), 
        .removeClass('loading')
        // then insert our image
        .append(this);

      // fade our image in to create a nice effect
      $(this).fadeIn();
    })

    // if there was an error loading the image, react accordingly
    .error(function () {
      // notify the user that the image could not be loaded
    })

    // *finally*, set the src attribute of the new image to our image
    .attr('src', 'images/headshot.jpg');
});

Otros consejos

Se puede cargar la primera imagen, y luego, cuando se ha terminado de cargar, configurarlo como imagen de fondo. De esa manera el navegador (con suerte) cargar la imagen de fondo de la memoria caché en lugar de volver a descargar la misma. A medida que ha solicitado como un plugin:

 $.fn.smartBackgroundImage = function(url){
  var t = this;
  //create an img so the browser will download the image:
  $('<img />')
    .attr('src', url)
    .load(function(){ //attach onload to set background-image
       t.each(function(){ 
          $(this).css('backgroundImage', 'url('+url+')' );
       });
    });
   return this;
 }

Utilice esta manera:

 $('body').smartBackgroundImage('http://example.com/image.png');

No se puede utilizar imágenes de fondo de CSS, porque es imposible imponer un evento para la carga de las imágenes (hasta donde yo sé).

Así que voy a darle una oportunidad, pero no lo he probado:

HTML:

<body>
<div class="bgimage"><img src="/bgimage.jpg" ></div>
<div>
  ... content ...
</div>
</body>

CSS:

.bgimage { position: absolute: }

Javascript:

$(function() {
   $(".bgimage")
      .css("opacity",0);
      .load(function() { $(this).fadeIn(); });
});

Usted puede ir con el siguiente truco, lo siento si es un poco sucio.

Guión:

        jQuery.preloadImages = function() {
        for (var i = 0; i < arguments.length; i++) {
            jQuery("<img>").attr("src", arguments[i]);
            $('.box1').attr('preloadURL', arguments[0]);
        }
    }

    $.preloadImages("sky.jpg");

    $(document).ready(function() {
        if ($('.box1').attr('preloadURL') == 'sky.jpg') {
            $('.box1').css({ 'background-image': 'url(sky.jpg)' },$('.box1').fadeIn(1000));
        }
    });

Marcado:

<div class="Content">
        <label>Search Bing</label>
        <input type="text" />
        <input type="button" value="search" />
    </div>
<div class="box1"></div>

CSS:

.box1 {background-repeat:no-repeat; width:800px; height:600px; display:none; position:relative;}
    .Content { position:absolute; left:20px; top:20px; z-index:100;}
    .Content label { color:White;}

esperanza esto ayuda

Una pequeña muestra de encendido: http://xgreen.co.uk/test.htm

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top