这是我使用的方法
CSS:
#div_whatever {
position: whatever;
background-repeat: no-repeat;
background-position: whatever whatever;
background-image: url(dir/image.jpg);
/* image.jpg is a low-resolution at 30% quality. */
}
#img_highQuality {
display: none;
}
HTML:
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的低分辨率图像.
PURE JS VERSION
这个例子对于将一个元素更改为多个元素将是有效的.
CSS:
.hidden {
display: none;
}
#div_whatever {
position: whatever;
background-repeat: no-repeat;
background-position: whatever whatever;
background-image: url(dir/image.jpg);
/* image.jpg is a low-resolution at 30% quality. */
}
HTML:
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
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 + ")");
});
});
发生什么事:
>根据他们的CSS为每个div加载低分辨率图像背景图像设置. (请注意,CSS还将div设置为预期尺寸.)>同时,分辨率较高的照片正在进行中作为隐藏图像加载(所有共享类名img_highres).>每次img_highres照片都会触发一个jQuery函数完成加载.> jQuery函数读取图像src路径,和改变相应div的背景图像.在里面在上面的例子中,命名约定是可见div的“div_ [name]”和“img_ [同名]”用于加载的高分辨率图像背景.