首页 > 解决方案 > 在 HTML 上单击图像时显示图像和文本

问题描述

在尝试让网站以下列方式做出响应时,我需要帮助:我希望能够单击图像,然后会在该图像旁边显示图像和一些信息。我已经实现了显示图像的部分,但不知道如何在它旁边显示文本。这是我到目前为止所拥有的:

<div class="image center">
      <a href="images/123.jpg"><img src="images/123.jpg" alt="" /></a>
<p class="color names">123</p>
</div>

这基本上只是放大了屏幕上的图像。

标签: javascripthtmlcss

解决方案


为了在单击图像时显示文本,您需要为其编写一个函数。

我在这里做了一个非常简单的例子,当点击图像时会出现一个文本,然后当你再次点击它时会消失。您可以根据需要修改代码。

HTML

<div class="image center">
  <a href="#" onClick="showStuff()">
    <img src="images/123.jpg" /></a>
    <p class="color names">123</p>
</div>
# Here's the part that shows/hides when you click the image
<div id="hidden" style="display: none"><p>Here's the hidden text</p> 
</div>

Javascript

function showStuff() {
  let hidden = document.getElementById('hidden');
  if (hidden.style.display == "none") {
    hidden.style.display = "block"
  } else {
    hidden.style.display = "none"
  }
}

推荐阅读