如何使用 JavaScript 显示图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5451445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display image with JavaScript?
提问by ivanz
I am trying to display image, through JavaScript, but i can't figure out how to do that. I have following
我试图通过 JavaScript 显示图像,但我不知道如何做到这一点。我有以下
function image(a,b,c)
{
this.link=a;
this.alt=b;
this.thumb=c;
}
function show_image()
{
document.write("img src="+this.link+">");
}
image1=new image("img/img1.jpg","dsfdsfdsfds","thumb/img3");
in HTML
在 HTML 中
<p><input type="button" value="Vytvor" onclick="show_image()" > </p>
I can't figure out where should I put something like image1.show_image();
.
我不知道我应该把类似的东西放在哪里image1.show_image();
。
HTML? Or somewhere else...
HTML?或者别的地方...
回答by jessegavin
You could make use of the Javascript DOM API. In particular, look at the createElement()method.
您可以使用Javascript DOM API。特别是,看看createElement()方法。
You could create a re-usable function that will create an image like so...
您可以创建一个可重复使用的函数,该函数将创建一个像这样的图像......
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
那么你可以像这样使用它......
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>