【问题标题】:Add/remove CSS class based on #hash基于 #hash 添加/删除 CSS 类
【发布时间】:2016-06-03 11:17:37
【问题描述】:

我的网站上有两种表格。一个.login-form 和一个.registration-form。默认情况下,登录表单具有display: block 属性,而注册表单具有display: none 属性。我有一个按钮可以在两种形式之间切换。已经很好用了。

现在我想根据 url 哈希切换这些属性。所以如果你访问/user.html#registration,我想先看注册表格而不是登录表格。

我怎样才能做到这一点? 非常感谢您的帮助!

jaro.

【问题讨论】:

标签: javascript jquery html css class


【解决方案1】:

读取哈希的简短脚本应该这样做:

<script>
// Add this block to where your "after page load" code starts. 
// If you use a framework, you should adjust the solution to your framework.
if (location.hash && location.hash === "#registration") {
    // or whichever way your app switches between the two
    document.body.classList.add("show-registration");
} // else it'll show login, as intended.
</script>

如果您的 CSS 尚未设置:

<style>
body.show-registration .login-form {
    display: none;
}
body.show-registration .registration-form {
    display: block;
}
</style>

【讨论】:

    【解决方案2】:

    我认为这正是您正在寻找的:

    window.addEventListener("hashchange", () => {
      if (window.location.hash === "registration") {
         document.querySelector(".registration-form").style.display = "block";
      }
    });
    

    【讨论】:

    • 但这不是添加类,而是直接更改样式属性。如果你定义你的类,你可以做 document.querySelector(".registration-form").classList.add("your class") 或 .classList.remove("your class");
    • 不客气,如果它解决了你的问题,请你批准答案
    猜你喜欢
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 2012-09-15
    • 2011-08-23
    • 2019-09-18
    • 2011-01-11
    • 1970-01-01
    相关资源
    最近更新 更多