在 HTML 中显示/隐藏 UI 元素时出现问题



我写了一些HTML来在单击按钮时显示/隐藏一些UI。 我希望在页面加载时隐藏UI,并在单击"显示UI"按钮时显示UI。

以下 HTML 几乎可以工作:

function showHide(thingToHide, thingToShow) {
  document.getElementById("status").innerHTML = "Shown";
  if (thingToHide == "showUI") {
    document.getElementById("status").innerHTML = "Hidden";
  }
  document.getElementById(thingToHide).style.visibility = "hidden";
  document.getElementById(thingToShow).style.visibility = "visible";
}
<div id="hideUI">
  <input id="showButton" type="button" onclick="showHide('hideUI', 'showUI');" value="Show UI" />
</div>
<div id="showUI">
  <input id="hideButton" type="button" onclick="showHide('showUI', 'hideUI');" value="Hide UI" />
  <p> Various UI goes here</p>
</div>
<p id="status">Start</p>

但是,"showUI"div 在页面首次显示时可见。 如果我在该div 中将初始可见性设置为隐藏,则当我单击"显示 UI"按钮并尝试使其可见时,它不会按预期显示。

<div id="showUI" style="visibility: hidden;">

您只需要在脚本中调用该函数一次。请参阅下面的代码,我在声明函数后刚刚调用了showHide('show', 'hideUI');

function showHide(thingToHide, thingToShow) {
  document.getElementById("status").innerHTML = "Shown";
  if (thingToHide == "showUI") {
    document.getElementById("status").innerHTML = "Hidden";
  }
  document.getElementById(thingToHide).style.visibility = "hidden";
  document.getElementById(thingToShow).style.visibility = "visible";
}
showHide('showUI', 'hideUI');
<div id="hideUI">
  <input id="showButton" type="button" onclick="showHide('hideUI', 'showUI');" value="Show UI" />
</div>
<div id="showUI">
  <input id="hideButton" type="button" onclick="showHide('showUI', 'hideUI');" value="Hide UI" />
  <p> Various UI goes here</p>
</div>
<p id="status">Start</p>

加载页面时需要执行 showHide('hideUI', 'showUI')。以下Javascript应该可以工作:

function showHide(thingToHide, thingToShow) {
  document.getElementById("status").innerHTML = "Shown";
  if (thingToHide == "showUI") {
    document.getElementById("status").innerHTML = "Hidden";
  }
  document.getElementById(thingToHide).style.visibility = "hidden";
  document.getElementById(thingToShow).style.visibility = "visible";
}
showHide('hideUI', 'showUI');

我的原始代码的问题在于javascript函数在divs之前。 如果我将div showUI 的可见性设置为隐藏在 HTML 中,并且我将 javascript 移动到div 的 HTML 之后,它会根据需要工作。

这可能是你要找的。它将按钮保持在同一个位置。

.HTML

<input id="Button" type="button" onclick="showHide('UI');" value="Show UI" />
<div id="UI" style="visibility: hidden">
    <p> Various UI goes here</p>
</div>
<p id="status">Start</p>

.JS

function showHide(UI) {
  if (document.getElementById(UI).style.visibility === 'hidden') {
    document.getElementById("status").innerHTML = "Shown";
    document.getElementById(UI).style.visibility = "visible";
    document.getElementById('Button').value = 'Hide UI'
  } else {
    document.getElementById("status").innerHTML = "Hidden";
    document.getElementById(UI).style.visibility = "hidden";
    document.getElementById('Button').value = 'Show UI'
  }

最新更新