使用javascript将Image对象设置为div背景图像 [英] Set an Image object as a div background image using javascript

查看:807
本文介绍了使用javascript将Image对象设置为div背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从背景中加载4个图像,向客户端显示加载条

,当下载图像时,我想将它们设置为4个div块的背景图像。

I want to load 4 images from background showing a load bar to the client
and when the images will be downloaded i want to set them as background images to 4 div blocks.

我正在寻找类似的东西。

I am looking for something like this.

var myImages = new Array();
for(var i = 0; i < 4; i++)
    myImages[i] = new Image();
//load images using the src attribute
//and execute an on load event function where to do something like this.
var div0 = document.getElementById('theDivId');
div0.style.backgroundImage = myImage[index];

有没有办法使用Image javascript对象设置背景图片?

Is there any way to set a background image using an Image javascript object?

推荐答案

你可以做一些接近你所拥有的事情。您没有将图像背景设置为图像对象,但可以从图像对象获取 .src 属性并将其应用于backgroundImage。成功加载图像对象后,浏览器将缓存图像,因此当您在任何其他对象上设置.src时,图像将快速加载。你可以使用这种类型的代码:

You can do something close to what you had. You don't set an image background to be an image object, but you can get the .src attribute from the image object and apply that to the backgroundImage. Once the image object has successfully loaded, the image will be cached by the browser so when you set the .src on any other object, the image will load quickly. You could use this type of code:

var imgSrcs = [...];   // array of URLs
var myImages = [], img;
for (var i = 0; i < 4; i++) {
    img = new Image();
    img.onload = function() {
        // decide which object on the page to load this image into
        // this part of the code is missing because you haven't explained how you
        // want it to work
        var div0 = document.getElementById('theDivId');
        div0.style.backgroundImage = "url(" + this.src + ")";
    };
    img.src = imgSrcs[i];
    myImages[i] = img;
}

此代码缺少部分是决定加载页面上的哪些对象当图像成功加载时,如果图像加载成像,你只需将它们加载到相同的页面对象中,只要它们全部加载,这可能不是你想要的。由于我真的不知道你想要什么,而你没有指明,我无法填写代码的那一部分。

The missing part of this code is deciding which objects on the page to load which image into when the image loads successfully as your example stood, you were just loading each one into the same page object as soon as they all loaded which probably isn't what you want. As I don't really know what you wanted and you didn't specify, I can't fill in that part of the code.

有一点需要注意使用带图像的 .onload 事件时,您必须在设置<$ c之前设置 .onload 处理程序$ c> .src 属性。如果你不这样做,你可能会错过 .onload 事件,如果图像已被缓存(因此它会立即加载)。

One thing to watch out for when using the .onload event with images is you have to set your .onload handler before you set the .src attribute. If you don't, you may miss the .onload event if the image is already cached (and thus it loads immediately).

这篇关于使用javascript将Image对象设置为div背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆