首页 > 解决方案 > 单击单个图像以使其消失的问题

问题描述

我遇到了通过单击它们使单个图像消失的问题。不太确定是因为图像堆叠还是与我的功能有关。

这是我到目前为止所拥有的:

<head>
<style> 
  body {
  background-image: url("a2_page_4.JPG");
  background-size: cover;
  background-attachment: fixed;
  position: fixed;
  margin: 0;
  padding: 0;
  }

  .image1 {
  position: relative;
  }

  .image2 {
  position: absolute;
  } 
</style>
</head>
<body>
  <img class="image2" id="person" src="person1.PNG" onclick="myFunction">
  <img class="image2" id="person" src="person2.PNG" onclick="myFunction">
  <img class="image2" id="person" src="person3.PNG" onclick="myFunction">
  <img class="image2" id="person" src="person4.PNG" onclick="myFunction">
  <img class="image1" id="person" src="person5.PNG" onclick="myFunction">
</body>
<script>
  function myFunction() {
  document.getElementById("person").style.display = "none";
  }
</script>

标签: javascripthtmlcss

解决方案


问题是您隐藏了一个名为“person”的元素,但您有多个具有相同 ID 的元素(您不应该有多个具有相同 ID 属性的元素)。您想要隐藏被点击的元素。

可以为您工作的代码。

<html>
<head>
    <style>

        .image1 {
            position: relative;
            border: 1px solid red;
        }

        .image2 {
            position: absolute;
            border: 1px solid green;
        }
    </style>
</head>
<body>
    <img class="image2"  src="https://via.placeholder.com/150" onclick="myFunction(this)">
    <img class="image2"  src="https://via.placeholder.com/170" onclick="myFunction(this)">
    <img class="image2"  src="https://via.placeholder.com/190" onclick="myFunction(this)">
    <img class="image2"  src="https://via.placeholder.com/210" onclick="myFunction(this)">
    <img class="image1"  src="https://via.placeholder.com/230" onclick="myFunction(this)">
</body>
<script>
    function myFunction(img) {
        img.style.display = "none";
    }
</script>

</html>


推荐阅读