使用JavaScript单击按钮时显示和隐藏图片

vd8tlhqk  于 2023-04-04  发布在  Java
关注(0)|答案(2)|浏览(182)

我想显示一个图片时,我点击一个按钮(上),当我点击按钮(关闭)将隐藏图片和显示图片关闭
我有这个代码的javascript运行按钮(上)显示图片和按钮(关闭)隐藏图片上,所以我需要显示图片关闭时,点击按钮关闭和隐藏时,点击按钮。

<button id="show-image-button"  style="--clr:#0FF0FC"><span>on</span><i></i></button>
  <br>
  <button  onclick="myFunction()"  style="--clr:#0FF0FC"><span>off</span><i></i></button>
  <br>
  <img id="my-image"  src="pump on.gif" alt="anim" style=" text-align: center;  justify-content:center;display: none;width:130px;height:130px;">
  <br>
  <img  src="pump off.png" alt="anima" style="display: none;width:120px;height:100px;">
  <br>
  
    <script>
   
    function myFunction() {
        document.getElementById("my-image").style.visibility = "hidden";
      
        
      }
      const showImageButton = document.getElementById("show-image-button");
      const myImage = document.getElementById("my-image"); 
      showImageButton.addEventListener("click", () => { 
         myImage.style.display = "block"; 
  
      }
      );
   
    </script>
f0brbegy

f0brbegy1#

hi尝试使用if语句,然后在你的按钮上使用测试函数,你可以使用箭头函数或常规函数方法

let show = true  
let test = () => {
   if (show == true) {
     document.getElementById("sth").style.display = "none"
      show = false
    } 
 else {
     document.getElementById("sth").style.display = "block"
      show = true
    }
}
<img id="sth" src="something"/>
8yoxcaq7

8yoxcaq72#

简化函数法

function myFunction(val) {
     
     const imgHolder = document.getElementById("my-image");
     const images = {
          off : "pump off.png", 
          on: "pump on.png"
     }

   if(!val) { imgHolder.classList.add('d-none'); return };
    
     imgHolder.classList.remove('d-none')
     imgHolder.setAttribute('src', images[val])
     imgHolder.setAttribute('alt', images[val]) // Optional
 
 }
.d-none { display: none; }
<button onclick="myFunction('on')">
  <span>on</span>
</button>
<br />
<button onclick="myFunction('off')">
   <span>off</span>
</button>

<br />

<img id="my-image" src="pump on.gif" alt="anim ON" class="d-none" />

相关问题