Set an Image object as a div background image using javascript

一个人想着一个人 提交于 2019-11-27 20:15:45

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.

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).

This way, the image shows up instantly all in one once it's loaded rather than line by line.

function setBackgroundImage(){
    imageIsLoaded(myURL).then(function(value) {
        doc.querySelector("body > main").style.backgroundImage = "url(" + myURL + ")";
    }
}
function imageIsLoaded(url){
    return new Promise(function(resolve, reject){
        var img = new Image();
        try {
            img.addEventListener('load', function() {
                resolve (true);
            }, false);
            img.addEventListener('error', function() {
                resolve (false);
            }, false);      
        }
        catch(error) {
            resolve (false);
        }
        img.src = url;
    });        
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!