如何在html中单击按钮时更改图像

时间:2016-12-11 18:46:11

标签: html

我正在学习HTML,我想知道如何在点击按钮时更改图像。这就是我到目前为止的代码: -



<button onclick="document.getElementById('myImage').src='https://www.google.co.uk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'">change image</button>

<img id="myImage" src="https://www.google.co.uk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" width="800" height="600" longdesc="https://www.google.co.uk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
&#13;
&#13;
&#13;

我希望能够在单击按钮时更改图像。 因此,如果图像是谷歌,那么当单击按钮时我想要ubuntu出现,如果图像是ubuntu,那么当点击按钮时我想要Firefox。我使用多个按钮完成了它,但我不知道如何使用一个按钮来更改图像。

如果有人可以帮助我那会很棒。

1 个答案:

答案 0 :(得分:0)

以下是使用Javascript切换图片的示例。计数器运行1-3并相应地显示图像。有关每个部件的说明,请参阅注释。如果您希望将其扩展为更多图像,则可以创建一个图像数组,然后在数组中递增,显示每个图像,直到达到数组长度,此时您可以再次从数组的开头开始。

&#13;
&#13;
var x = 1; //initializes counter
function switchImg() {
  if (x == 1) { //if the counter is at 1
    document.getElementById("imgToSwitch").src = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcR7pz7PYv3YJ1R391uzau_CS-kXxgpWG8zrDtam-LsUK50KEAM4_wIgKg";
    x++; //increments the counter to 2
  } else if (x == 2) { //if this is the 2nd click
    document.getElementById("imgToSwitch").src = "https://www.mozilla.org/media/img/styleguide/identity/firefox/guidelines-logo.7ea045a4e288.png";
    x++; //increments counter to 3
  } else if (x == 3) { //if the counter is 3
    document.getElementById("imgToSwitch").src = "https://www.wired.com/wp-content/uploads/2015/09/google-logo-1200x630.jpg";
    x = 1; //resets counter to 1
  }
}
&#13;
/*not needed. Just used to make everything pretty. */

body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
img {
  height: 110px;
}
&#13;
<!--calls the function when it is clicked -->
<button type="button" onclick="switchImg()">Click Me!</button>
<!--image with id of "imgToSwitch." This is the content that is targeted -->
<img src="https://www.wired.com/wp-content/uploads/2015/09/google-logo-1200x630.jpg" id="imgToSwitch">
&#13;
&#13;
&#13;