gpt4 book ai didi

javascript - 如何使用 JavaScript 更改 CSS 显示属性?

转载 作者:行者123 更新时间:2023-12-02 23:52:44 24 4
gpt4 key购买 nike

我无法更改 img 标签的显示属性。

我已将显示更改为内联或 block 。

function toggle_btn_img() {

let btnId = document.getElementById("btn");
let avatarId = document.getElementById("avatar");

if (btnId.innerHTML === "Show!") {
avatarId.style.display = "block";
btnId.innerHTML = "Hide!";
} else {
avatarId.style.display = "none";
btnId.innerHTML = "Show!";
}
}
<div class="w3-display-container w3-card w3-col s4 w3-display-middle w3-light-gray" style="height: 30%;">
<div class="w3-display-right w3-col s6 w3-display-container">
<button id="btn" onclick="toggle_btn_img()" class="w3-btn w3-card w3-round w3-light-green w3-hover-green w3-text-white w3-text-hover-gray w3-display-middle w3-col s4">Show!</button>
</div>
<div class="w3-display-left w3-dispaly-container w3-col s6">
<div id="avatar_container" class="w3-card w3-circle w3-display-middle w3-pale-blue" style="height: 150px; width: 150px;"><img id="avatar" src='http://placekitten.com/200/300' class="w3-hide w3-col s11 w3-display-middle" /></div>
</div>
</div>

我希望图像显示和隐藏,但事实并非如此。 (我不能更改 html 或 css 文件!)

最佳答案

首先你必须通过CSS或JS隐藏它,否则第一次点击按钮将不会有任何效果。一旦你这样做了,你就会得到预期的结果:

let btnId = document.getElementById("btn");
let avatarId = document.getElementById("avatar");
avatarId.style.display = "none";

function toggle_btn_img() {

if (btnId.innerHTML === "Show!") {
avatarId.style.display = "block";
btnId.innerHTML = "Hide!";
} else {
avatarId.style.display = "none";
btnId.innerHTML = "Show!";
}
}
#avatar {
display: none;
}
<div class="w3-display-container w3-card w3-col s4 w3-display-middle w3-light-gray" style="height: 30%;">
<div class="w3-display-right w3-col s6 w3-display-container">
<button id="btn" onclick="toggle_btn_img()" class="w3-btn w3-card w3-round w3-light-green w3-hover-green w3-text-white w3-text-hover-gray w3-display-middle w3-col s4">Show!</button>
</div>
<div class="w3-display-left w3-dispaly-container w3-col s6" >
<div id="avatar_container" class="w3-card w3-circle w3-display-middle w3-pale-blue" style="height: 150px; width: 150px;"><img id="avatar" src='//placekitten.com/200/300' class="w3-hide w3-col s11 w3-display-middle"/></div>
</div>
</div>

关于javascript - 如何使用 JavaScript 更改 CSS 显示属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55569584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com