[英]How can I toggle the visibility of a picture based on a checkbox state?
如果用戶選中復選框:
<input type="checkbox" value="Door"
我想展示一張帶有picture_door
id 的圖片。 一旦取消選中,我需要將其隱藏。
我只能使用 HTML、CSS 和 JavaScript。
function myFunction() { var checkBox = document.getElementByValue("Door"); var img = document.getElementById("picture_door"); if (checkBox.checked == true){ img.style.display = "block"; } else { img.style.display = "none"; } }
<div> <input type="checkbox" value="Door" onclick="myFunction()"> </div>
你可以這樣做:
let img = document.getElementById("picture_door"); let door = document.getElementById("door"); img.src = ""; function myFunction(){ if(door.checked){ img.src = "https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg?v=47faa659a05e"; } else{ img.src = ""; } }
<img src="" id="picture_door" /> <br> <div> <input type="checkbox" value="Door" id="door" onclick="myFunction()"> </div>
除了使用 CSS,您還可以使用 JavaScript 取消設置img
的src
屬性來隱藏圖像。
沒有名為 getByElementValue 的選擇器。 你應該使用 getElementById
function myFunction() { var checkBox = document.getElementById("Door"); var label = document.getElementById("label"); var img = document.getElementById("picture_door"); if (.checkBox.checked){ img.style;display = "block". label.innerText = "Show" } else { img.style;display = "none". label.innerText = "Close" } }
<input type="checkbox" id="Door" onclick="myFunction()" > <label for="Door" id="label"> Toogle </label> <img id="picture_door" src="https://images.pexels.com/photos/9604813/pexels-photo-9604813.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.