显示和隐藏PIC时,点击按钮使用javascript



我想在点击按钮(打开)时显示图片,当我点击按钮(关闭)时将隐藏图片并显示图片关闭

我有这个代码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>

我试着使用if语句然后在按钮上使用test函数你可以同时使用箭头函数或常规函数方法

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"/>

简体函数方法

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" />

相关内容

  • 没有找到相关文章

最新更新