褪色的背景图像

Vil*_*ger 20 jquery background-image

我有一个网页,使用大图像作为其背景.我希望在下载后使用jQuery加载图像(基本上就是bing.com加载其背景图像的方式).这有可能与jQuery?如果是这样,你会推荐一个插件吗?

Pim*_*ger 25

您可以先加载图像,然后在加载完成后将其设置为背景图像.这样浏览器(希望)将从缓存加载背景图像而不是重新加载它.正如您作为插件请求它:

 $.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;
 }
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

 $('body').smartBackgroundImage('http://example.com/image.png');
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢,但是如何让背景图片淡入? (6认同)

kgi*_*kis 11

这篇文章可能很有用.从那里复制:

HTML

<div id="loader" class="loading"></div>
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

使用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');
});
Run Code Online (Sandbox Code Playgroud)