简体   繁体   English

如何在单击按钮时加载图像?

[英]How to load an image on button click?

I'm kind of new to HTML / Javascript, and I'm trying to figure out how to make it so when I click a button, an image loads. 我是HTML / Javascript的新手,我试图弄清楚如何制作它,因此当我单击按钮时,将加载图像。 This is all I can come up with, but then again I am very bad with this stuff, and I am still learning greatly . 这就是我所能想到的全部,但是再说一遍,我对这些东西非常不好,而且我仍然在学习很多东西。

<html>
<div style="visibility:invisible" id="theTrick">
<img id="myImage" src="https://minecraft.net/images/logo.png" alt="Test">
</div>
<button type="button" onclick="myFunction">Click for the Minecraft Logo</button>
<script>
function myFunction() {

    document.getElementById="theTrick".style = "visibility:initial"

}
</script>
</html>

EDIT 编辑

I have solved this, and since then learned a LOT more, mastering HTML and CSS, and now learning the works of JavaScript. 我解决了这个问题,从那时起,我学到了很多东西,掌握了HTML和CSS,现在学习了JavaScript的作品。 I do have a question though to add on to this; 我确实有一个问题要补充: is there a way to have the image disappear on another click, then reappear on the next click, and so on? 有没有一种方法可以使图像在另一次单击时消失,然后在再次单击时重新出现,依此类推?

A few things: 一些东西:

  1. It's visibility: hidden , not visibility: invisible . 它是visibility: hidden ,而不是visibility: invisible
  2. It's myFunction() , not myFunction . 它是myFunction() ,而不是myFunction
  3. It's document.getElementById("theTrick") , not document.getElementById = "theTrick" . 它是document.getElementById("theTrick") ,而不是document.getElementById = "theTrick"
  4. It's visibility: visible , not visibility: initial (the initial visibility is hidden , which you've set at the top). 它是visibility: visible ,不是visibility: initial (初始可见性已hidden ,已在顶部设置)。

You may find this document on the CSS visibility property useful. 您可能会发现CSS visibility属性上的此文档很有用。

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM