[英]Pre-loading images to set as background-image
I am trying to pre-load some images and set them as background images. 我正在尝试预加载一些图像并将它们设置为背景图像。 I'm showing that the images are being loaded, but they're not being brought in as background images but rather, <img>
elements. 我正在显示图像正在加载,但它们不是作为背景图像引入,而是作为<img>
元素引入。 Is it not possible to pre-load background images? 无法预加载背景图像吗?
Function to pre-load the images 预加载图像的功能
function preloadImage(url){
var imgObj = new Image();
imgObj.src = url;
imgObj.onload = function(){
console.log(imgObj, "Loaded");
}
}
Object holds the image url's. 对象保存图像的URL。
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"]
}
}
Sets the background image 设置背景图片
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);
}
The preloadImage
function never returns a value, so the src
property is never set. preloadImage
函数从不返回值,因此从不设置src
属性。 To ensure that the objects do not get cleaned up after the function is called, I would return the object to a property: 为了确保在调用函数后不清除对象,我将对象返回到属性:
function preloadImage(url){
...
return imgObj;
}
var Plane_Images = {
Skin: {
name: "Skin Schematic",
image: preloadImage("images/Top.png"),
schematics: ["A", "B", "C", "D"]
},
}
And access the src by: 并通过以下方式访问src:
var image_src = current.image.src;
So, two answers: The function should return something. 因此,有两个答案:函数应该返回一些东西。 I would return the object, so the pre-loading will not get canceled if the Image Object is cleaned up after the function execution. 我将返回该对象,因此,如果在函数执行后清除Image Object,则不会取消预加载。
Also, your setting function looks a little off: 另外,您的设置功能看起来有点:
for(var images in Plane_Images){
Should probably read: 应该大概读为:
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.
See http://www.w3schools.com/js/js_loop_for.asp 参见http://www.w3schools.com/js/js_loop_for.asp
Here is an alternate way to preload images for use as the background-image property. 这是预加载图像以用作background-image属性的另一种方法。
body:after {
display: none;
content: url(img0.png) url(img1.png) url(img2.png);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.