Joni 的回答非常正确 - 但是在您学习时,请记住 HTML“只是”一个结构化文本文档,这将使您走得更远。一旦你准备好动态创建内容,就准备好学习大量的 DOM。但是,你似乎已经知道一些代码,所以这就是成功的一半。;)
为了让您了解如何使用 JS 执行此操作,您正在寻找的是Image
对象。您可以通过编写类似...的内容来创建新图像var myPicture = new Image();
。就目前而言,这在您的文档中尚不存在,并且它没有源 - 资源的路径,但您确实有对新图像的引用,您可以使用它来做事。
src
你可以通过改变它的属性来给它一个来源,就像这样myPicture.src="a.png";
:但是,您必须记住(这很重要)加载该图像的操作是异步的。这意味着如果您要将图像添加到文档中,则在加载图像之前您将看不到任何内容。图像是开始理解这一点的好地方。尝试在您的控制台(chrome 中的开发人员工具)中使用这些命令,看看它有什么不同。
var myPicture = new Image();
myPicture.src = 'a.png';
document.body.appendChild(myPicture); // may or may not show the image, depending on how long it takes to load, but should be almost instant on a localhost or file
var myEmptyPicture = new Image();
document.body.appendChild(myEmptyPicture); // you will see the empty image tag in the document
myEmptyPicture.onload = function(){
console.log('I have finished loading the picture!')
};
myEmptyPicture.src = 'b.png'; // you kept the reference to the image, so you can change its src attribute even while it is in the document - this is important for more advanced stuff, and it should log a message to your console
// last one, this will insert itself into the document once it has loaded
myAutomaticPicture = new Image();
myAutomaticPicture.onload = function(){
console.log('picture loaded, inserting into document');
document.body.appendChild(myAutomaticPicture); // should see it in the document now
}
myAutomaticPicture.src = 'c.png';
onload 属性的特殊之处在于它以一个函数作为其值。当图像完成加载时调用此函数。
要尝试的事情,更改 DOM 中已有元素的 src 属性,或使用 document.createElement 方法制作其他元素并附加它们(例如:)var heading = document.createElement('h1'); heading.innerHTML='hello'; document.appendChild(heading);
。
一旦你开始看到这一切是如何结合在一起的,这会很有趣……