首页 > 解决方案 > Js 显示/隐藏功能 -> 隐藏/显示

问题描述

我正在尝试制作一个简单的弹出表单 onClick 但我不希望它显示然后隐藏我想要隐藏 -> 显示我使用了这个: https://www.w3schools.com/howto/tryit.asp?文件名=tryhow_js_toggle_hide_show 我设置 display: none;

我什至尝试交换 if 语句,但没有一个起作用:

        <script>
        function show() {
          var x = document.getElementById("box");
          if (x.style.display === "none") {
            x.style.display = "block";
          } else {
            x.style.display = "none";
          }
        }
        </script>
<button onclick="show()">Sign-in/Log-in</button> 
    <!-- Login Pop-up -->
    <form id="box" method="post">
        <input id="text" type="text" name="user_name"><br><br>
        <input id="text" type="password" name="password"><br><br>
                
        <input id="button" type="submit" value="Login"><br><br>
                
        <a>Don't have an account? Sign-up </a>
    </form>

风格

button {
    margin-left: 20px;
    padding: 9px 25px;
    color:white;
    background-color: #eb266e;
    border: none;
    border-radius: 50px;
    cursor: painter;
    transition: all 0.3s ease 0s;
}

button:hover {
    color: #eb266e;
    background-color: white;
    border: 1px solid #eb266e;
}
    
#box {
    border: solid 1px black;
    width: 200px ;
    padding: 50px 0;
    text-align: center;
    background-color: lightblue;
    margin-top: 20px;
}

标签: javascripthtmljquerycss

解决方案


元素的 classList 上的功能切换在这里很有用。

只需设置一个名为 say 'hide' 的类,它设置为无显示,将框设置为最初具有该类,以便在加载时看不到它。

然后在每次单击按钮时切换该类。

function showunshow() {
  document.getElementById("box").classList.toggle('hide');
}
button {
  margin-left: 20px;
  padding: 9px 25px;
  color: white;
  background-color: #eb266e;
  border: none;
  border-radius: 50px;
  cursor: painter;
  transition: all 0.3s ease 0s;
}

button:hover {
  color: #eb266e;
  background-color: white;
  border: 1px solid #eb266e;
}

#box {
  border: solid 1px black;
  width: 200px;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
}

.hide {
  display: none;
}
<button onclick="showunshow()">Sign-in/Log-in</button>
<!-- Login Pop-up -->
<form id="box" method="post" class="hide">
  <input id="text" type="text" name="user_name"><br><br>
  <input id="text" type="password" name="password"><br><br>

  <input id="button" type="submit" value="Login"><br><br>

  <a>Don't have an account? Sign-up </a>
</form>


推荐阅读