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

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


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


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文件!)


胡子哥哥
浏览 133回答 3
3回答

哈士奇WWW

我解决了!&nbsp; function toggle_btn_img() {&nbsp; &nbsp; &nbsp; &nbsp; let btnId = document.getElementById("btn");&nbsp; &nbsp; &nbsp; &nbsp; let avatarId = document.getElementById("avatar");&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if (btnId.innerHTML.trim() === "Show!") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; btnId.innerHTML = "Hide!";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; avatarId.style.setProperty("display", "inline-block","important");&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; btnId.innerHTML = "Show!";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; avatarId.style.setProperty("display", "none","important");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; }

holdtom

我认为您的代码是正确的。只是演示错误。<button&nbsp;id="btn"&nbsp;onclick="toggle_btn_img()"&nbsp;class="w3-btn&nbsp;w3-card&nbsp;w3-round&nbsp;w3-light-green&nbsp;w3-hover-green&nbsp;w3-text-white&nbsp;w3-text-hover-gray&nbsp;w3-display-middle&nbsp;w3-col&nbsp;s4">Hide!</button>我改变了表演!=>隐藏!(按钮文字)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript