设置HTML< img> Javascript图像变量的元素 [英] Set HTML <img> element to Javascript image variable

查看:125
本文介绍了设置HTML< img> Javascript图像变量的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组图像变量,这些变量使用javascript进行了图像序列动画的预加载.我遇到的问题是将HTML中的img元素设置为使用这些图像之一.看来所有属性都是字符串?

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?

这是我在javascript中设置图像数组的方法:

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";
    }
}

我只是有一个 ^ img标签=动画" ^ 我想更改的html中.

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

推荐答案

您的代码看起来有效.

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`;
    }
}

现在您可以执行以下操作: document.body.appendChild(anim[0]);

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

我对此进行了测试,并且对我有用.

I tested this and it works for me.

如果您想即时更改src,则必须选择附加的元素并按如下方式更新其src:document.querySelectorAll('img')[0].src = newSourceVariable;.

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

这篇关于设置HTML&lt; img&gt; Javascript图像变量的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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