Set HTML

2019-09-16 10:25发布

问题:

I have an array of image variables that get preloaded using javascript to make an image sequence animation. The issue I have is setting the img element from HTML to use one of these images. It seems all the properies are strings?

Here's how I set the array of images in javascript:

for(var i = 0; i < 30; i ++){
    anim[i] = new Image();
    if(i < 10){
        anim[i].src = "images/anim/frame0" + i + ".png";
    }
    if(i >= 10){
        anim[i].src = "images/anim/frame" + i + ".png";
    }
}

and I simply have an ^img tag = "animation"^ in html that I want to change.

回答1:

Your code looks valid.

for(var i = 0; i < 30; i++){
    anim[i] = new Image();

    if(i < 10){
        anim[i].src = `images/anim/frame0${i}.png`;
    }

    if(i >= 10){
        anim[i].src = `images/anim/frame${i}.png`;
    }
}

Now you can do: document.body.appendChild(anim[0]);

I tested this and it works for me.

If you want to change src on the fly then you'd have to select the appended element and update its src like this: document.querySelectorAll('img')[0].src = newSourceVariable;.