基本上,我在名为 image0.png、image1.png、image(index).png
的文件夹中有图像,我想加载这些图像(预加载,这样它们就不会永远加载页面加载后)到 div 内的图像标签中。图片标签由DOM生成,然后初始化为默认参数。我遇到的问题是,我似乎无法让文档模型获取充满图像的数组并将其加载到图像标签 IMGTG.src = IMGS[0];
中?下面是代码
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript">
IMGS = new Array();
var IMGTG;
function INIT_IMGTG(id)
{
IMGTG = document.createElement("img");
IMGTG.setAttribute("height", "100%");
IMGTG.setAttribute("width", "100%");
IMGTG.setAttribute("border", "0");
}
function LOAD_IMGS()
{
var index = 0;
for(index = 0; i < 2; i++)
{
IMGS[i] = "image" + index + ".png"
}
}
function IMG_ARY(id)
{
LOAD_IMGS();
INIT_IMGTG(id);
IMGTG.src = IMGS[0];
}
</script>
</head>
<body onload = "IMG_ARY('IMG_ID')">
<div id="IMG_ID"></div>
</body>
</html>
编辑: 到目前为止,我按照两位回答者的描述进行了编辑,但仍然没有运气?我不知道是什么原因造成的,Javascript 是一种奇怪的语言。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript">
IMGS = new Array();
var IMGTG;
function INIT_IMGTG(id)
{
IMGTG = document.createElement("img");
IMGTG.setAttribute("height", "100%");
IMGTG.setAttribute("width", "100%");
IMGTG.setAttribute("border", "0");
id.appendChild(IMGTG);
}
function LOAD_IMGS()
{
for(var i = 0; i < 2; i++)
{
IMGS[i] = "image" + i + ".png";
}
}
function IMG_ARY(id)
{
LOAD_IMGS();
INIT_IMGTG(id);
IMGTG.src = IMGS[0];
}
</script>
</head>
<body onload = "IMG_ARY('IMG_ID')">
<div id="IMG_ID"></div>
</body>
</html>
最佳答案
看起来您已经正确设置了图像 (IMGTG
) 的 src
以及它的其他属性,但您实际上并未将其插入到DOM。
尝试将其添加到 IMG_ARY
的底部:
id.appendChild(IMGTG);
关于Javascript DOM 将图像数组加载到 div 背景中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15489858/