如何用JavaScript显示图像?

iva*_*anz 19 html javascript image object

我试图通过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");
Run Code Online (Sandbox Code Playgroud)

在HTML中

<p><input type="button" value="Vytvor" onclick="show_image()" > </p>
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚我应该把它放在哪里image1.show_image();.

HTML?或者别的地方...

jes*_*vin 42

您可以使用Javascript DOM API.特别是,请查看createElement()方法.

您可以创建一个可重复使用的功能,将创建一个像这样的图像...

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);
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它......

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 
Run Code Online (Sandbox Code Playgroud)

查看jsFiddle上的一个工作示例:http://jsfiddle.net/Bc6Et/

  • 小提琴显示了一个名为“添加 Google 徽标”的按钮。按下时,文本“Google 徽标”会添加到右侧。没有图像可见。我检查了 logo.gif 图像是否存在并收到 404 错误。当我将其更改为现有地址(https://www.pinterest.at/pin/340655159306311689/)时,它又做了同样的事情。使用 Google Chrome 版本 60.0.3112.113(官方版本)(64 位)测试 (2认同)