【问题标题】:# url section hide and show# url 部分隐藏和显示
【发布时间】:2017-01-11 20:22:49
【问题描述】:

您好,我有一个带有 # 个部分的简单单页网站。我正在使用 # 来隐藏和显示部分。

例如; someurl/index.html/#sectionOne 有带有“sectionOne” id 的 div,所以我可以显示相关部分。

我的问题是有办法防止或替换 "/" 路径字符# 类似;

someurl/index.html/sectionOne --> someurl/index.html/#sectionOne

因为它当然会给出 404。 我试过 beforeunload、window on load、body on load,但这些都没有解决我的问题。

这是一个简单的例子

$(document).ready(function() {
    window.onload = function(event) {
        var hash = "about";
        $("section").hide();
        $("#" + hash).show();
    };

    $(".nav").click(function() {
        console.log("CLICK");
        var hash = $(this).attr('href').substring(1);
        console.log(hash);
        $("section").hide();
        $("#" + hash).show();
    });
});
section {display: none;}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<ul>
    <li><a class="nav" href="#about">ABOUT</a></li>
    <li><a class="nav" href="#services">SERVICES</a></li>
    <li><a class="nav" href="#contact">CONTACT</a></li>
</ul>

<section id="about">
    <h1>ABOUT</h1>
    <p>About section</p>
</section>

<section id="services">
    <h1>SERVICES</h1>
    <p>Services section</p>
</section>

<section id="contact">
    <h1>CONTACT</h1>
    <p>Contact section</p>
</section>

【问题讨论】:

    标签: javascript jquery html redirect


    【解决方案1】:

    如果我理解正确,这里可以使用target 伪类:

    section {
      display: none;
    }
    #about:target,
    #services:target,
    #contact:target {
      display: block;
    }
    <ul>
      <li><a class="nav" href="#about">ABOUT</a>
      </li>
      <li><a class="nav" href="#services">SERVICES</a>
      </li>
      <li><a class="nav" href="#contact">CONTACT</a>
      </li>
    </ul>
    
    <section id="about">
      <h1>ABOUT</h1>
      <p>About section</p>
    </section>
    
    <section id="services">
      <h1>SERVICES</h1>
      <p>Services section</p>
    </section>
    
    <section id="contact">
      <h1>CONTACT</h1>
      <p>Contact section</p>
    </section>

    关于防止用户使用/ 导航离开(不管它是什么),我相信没有简单的方法可以单独从客户端完成。

    我们可以使用window.onbeforeunload 事件并显示一个对话框,以根据用户是否想要让他们留在里面。

    我看到的另一个选项是使用React Router for client-side 404

    【讨论】:

    • 非常感谢,但我不是这个意思。我想要阻止用户输入“/”路径字符,或者如果有“/”路径字符而不是“#”哈希,请将其替换为 #。 someurl/index.html/about --> someurl/index.html#about
    • 明白你的意思。关于防止用户使用/ 导航离开(让它成为任何东西),我相信没有简单的方法可以仅从客户端完成。用一些建议更新了答案。
    猜你喜欢
    • 2010-10-01
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多