这是我使用的方法
CSS:
#div_whatever { position: whatever; background-repeat: no-repeat; background-position: whatever whatever; background-image: url(dir/image.jpg); }#img_highQuality { display: none;}HTML:
<img id="img_highQuality" src="dir/image.png"><!-- img.png is a full-resolution image. --><div id="div_whatever"></div>
JQUERY:
$("#img_highQuality").off().on("load", function() { $("#div_whatever").css({ "background-image" : "url(dir/image.png)" });});// Side note: I usually define CSS arrays because// I inevitably want to go back and add another // property at some point.怎么了:
- 低分辨率版本的背景会快速加载。
- 同时,高分辨率版本正在作为隐藏图像加载。
- 加载高分辨率图像时,jQuery将div的低分辨率图像替换为高分辨率版本。
纯JS版本
此示例对于更改一个到多个元素将非常有效。
CSS:
.hidden { display: none;}#div_whatever { position: whatever; background-repeat: no-repeat; background-position: whatever whatever; background-image: url(dir/image.jpg); }HTML:
<div id="div_whatever"></div><img id="img_whatever" src="dir/image.png" onload="upgradeImage(this);">
JAVAscript:
function upgradeImage(object) { var id = object.id; var target = "div_" + id.substring(4); document.getElementById(target).style.backgroundImage = "url(" + object.src + ")";}更新/增强(1/31/2017)
此增强功能的灵感来自gdbj的出色之处,即我的解决方案导致在三个位置指定了图像路径。尽管我没有使用gdbj的addClass()技术,但以下jQuery代码经过修改以提取图像路径(而不是将其硬连线到jQuery代码中)。更重要的是,此版本允许从低分辨率到高分辨率的多个图像替换。
CSS
.img_highres { display: none;}#div_whatever1 { width: 100px; height: 100px; background-repeat: no-repeat; background-position: center center; background-image: url(PATH_TO_LOW_RES_PHOTO_1);}#div_whatever2 { width: 200px; height: 200px; background-repeat: no-repeat; background-position: center center; background-image: url(PATH_TO_LOW_RES_PHOTO_2);}HTML
<div id="div_whatever1"></div><img id="img_whatever1" src="PATH_TO_HIGH_RES_PHOTO_1"><div id="div_whatever2"></div><img id="img_whatever2" src="PATH_TO_HIGH_RES_PHOTO_2">
JQUERY
$(function() { $(".img_highres").off().on("load", function() { var id = $(this).attr("id"); var highres = $(this).attr("src").toString(); var target = "#div_" + id.substring(4); $(target).css("background-image", "url(" + highres + ")"); }); });发生什么事:
- 根据其div的CSS背景图像设置为每个div加载低分辨率图像。(请注意,CSS还将div设置为预期的尺寸。)
- 同时,将更高分辨率的照片作为隐藏图像加载(所有共享类名均为img_highres)。
- 每次img_highres照片完成加载时,都会触发jQuery函数。
- The jQuery function reads the image src path, and changes the background image of the corresponding div. In the example above, the naming convention is “div_[name]” for the visible divs and “img_[same name]” for the high res images loaded in the background.



