我正在尝试预加载一些图像并将其设置为背景图像。我显示图片正在加载,但它们不是作为背景图片引入的,而是<img>
元素。是否无法预加载背景图像?
预加载图像的功能
function preloadImage(url){
var imgObj = new Image();
imgObj.src = url;
imgObj.onload = function(){
console.log(imgObj, "Loaded");
}
}
对象保存图片网址。
var Plane_Images = {
Skin: {
name: "Skin Schematic",
src: preloadImage("images/Top.png"),
schematics: ["A", "B", "C", "D"]
},
Structure: {
name: "Structure Schematic",
src: preloadImage("images/ata21.png"),
schematics: ["E", "F", "G", "H"]
},
Electrics: {
name: "Electrics Schematic",
src: preloadImage("images/ata26.png"),
schematics: ["I", "J", "K", "L"]
},
Fuel: {
name: "Fuel Schematic",
src: preloadImage("images/Top.png"),
schematics: ["M", "N", "O", "P"]
}
}
设置背景图片
for(var images in Plane_Images){
var schematic = $("<div data-id='" +id +"_menu' data-url='" +image_src +"'><div class='label'><p>" +images +"</p></div></div>");
schematic.addClass("schematics");
schematic.css("background-image", "url(" +image_src +")");
$("#menu").append(schematic);
}
答案 0 :(得分:2)
preloadImage
函数永远不会返回值,因此永远不会设置src
属性。为了确保在调用函数后不会清理对象,我会将对象返回到属性:
function preloadImage(url){
...
return imgObj;
}
var Plane_Images = {
Skin: {
name: "Skin Schematic",
image: preloadImage("images/Top.png"),
schematics: ["A", "B", "C", "D"]
},
}
通过以下方式访问src:
var image_src = current.image.src;
所以,两个答案:函数应该返回一些东西。我会返回该对象,因此如果在执行函数后清除了图像对象,则不会取消预加载。
此外,您的设置功能看起来有点偏差:
for(var images in Plane_Images){
应该读一下:
for(var image_name in Plane_images){
var current = Plabe_images[image_name];
var image_src = current.image.src; // Or however you store the source.
答案 1 :(得分:1)
这是另一种预加载图像以用作背景图像属性的方法。
body:after {
display: none;
content: url(img0.png) url(img1.png) url(img2.png);
}