【问题标题】:Showing Hidden Image With Onclick Function使用 Onclick 功能显示隐藏的图像
【发布时间】:2021-09-30 05:24:18
【问题描述】:

我的目标是在按下按钮之前隐藏图像,然后显示之前隐藏的图像。

现在我有一个 html 中的图像,其 ID 为“yellowrose”,该代码隐藏在此代码中:

    <div id="yellowrose"><img src="https://i.imgur.com/ppfhZa6.jpg" style="visibility:hidden"></div>

在 JS 中,buttonx.onclick 发生了几件事,但我似乎无法使图像可见。这是我的 JS 代码:

    var content = document.getElementById("content");
var buttonx = document.getElementById("show-more");
let yellowrose = document.getElementById("yellowrose");


window.onload = function(){
    
buttonx.onclick = function () {
    document.getElementById("yellowrose").style.visibility="visible";
          if(content.className == "open") {
              //shrink the box
              content.className = "";
              buttonx.innerHTML = "Continue to the Sunlit Pavillion?";
          } else{
              //expand the box
              content.className = "open";
              buttonx.innerHTML = "As you wander through the garden grounds you notice a striking Yellow Rose";
              
          }

          }
        }

您对如何通过 buttonx.onclick 函数使“黄玫瑰”图像可见有什么建议吗?谢谢。

【问题讨论】:

  • 请将 img 标记中的 style="visibility:hidden" 移动到您的 &lt;div id="yellowrose"&gt;,因为您的 JavaScript 定位到 yellowrose,即 div 标记不是 img 标签。

标签: javascript html button visibility hidden


【解决方案1】:

id 不能包含空格。

根据MDN

id值不得包含空格(空格、制表符等)。浏览器将包含空格的不合格 ID 视为空格是 ID 的一部分。与允许使用空格分隔值的 class 属性相比,元素只能有一个 ID 值。

此外,您设置的是#yellowrosevisibility,即图像的容器,而不是图像本身。要解决这个问题,只需获取 firstChild 属性:

var content = document.getElementById("content");
var buttonx = document.getElementById("showmore");
let yellowrose = document.getElementById("yellowrose");


window.onload = function() {

  buttonx.onclick = function() {
    document.getElementById("yellowrose").firstChild.style.visibility = "visible";
    if (content.className == "open") {
      //shrink the box
      content.className = "";
      buttonx.innerHTML = "Continue to the Sunlit Pavillion?";
    } else {
      //expand the box
      content.className = "open";
      buttonx.innerHTML = "As you wander through the garden grounds you notice a striking Yellow Rose";

    }

  }
}
.open{
  visibility:visible !important;
}
<div id="yellowrose"><img src="https://i.imgur.com/ppfhZa6.jpg" style="visibility:hidden"></div>
<button id="showmore">Show More</button>
<div id="content">
content
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多