繁体   English   中英

隐藏索引页的 URL 路径名和哈希

[英]Hide URL pathname and hash for index page

我有 2 页主页和服务。 在第一页(主页)中,使用 id 从导航栏平滑滚动到关于、联系、为什么。 从第二页(服务)如果点击第一页(主页)的 ABOUT 或 CONTACT 使用 id,它会显示准确的位置,但获取 URL 像https://www.example.com/index#abouthttps://www.example.com/index#contact

第一页(主页)的代码如下。

    <nav>
         <ul class="nav navbar-nav navbar-right">
          <li class="active"><a class="smooth_scroll" href="#slider">HOME</a></li>
          <li><a class="smooth_scroll" href="#about">ABOUT</a></li>
          <li><a href="service.html">SERVICES</a></li>
          <li><a class="smooth_scroll" href="#whyus">WHY US</a></li>
          <li><a class="smooth_scroll" href="#contact">CONTACT</a></li>
        </ul>
    </nav>

第二页(服务)的代码如下。

<div class="navbar-collapse collapse">
  <nav>
     <ul class="nav navbar-nav navbar-right">
       <li><a href="index.html">HOME</a></li>
       <li><a href="index.html#about">ABOUT</a></li>
       <li class="active"><a href="/service.html">SERVICES</a></li>
       <li><a href="index.html#pricing">WHY US</a></li>
       <li><a href="index.html#contact">CONTACT</a></li>
     </ul>
  </nav>
</div>

从页面导航时,如何获取像https://www.example.com而不是https://www.example.com/index#abouthttps://www.example.com/index#contact这样的 URL二(服务)到第一页(主页),我不希望在 URL 中显示index#id

所以,请建议如何使用 Javascript/Jquery/Html/Css 等删除它。

尝试完整链接并在 index.php 上重命名 index.html

https://www.example.com/(index.php 如果是索引页,可以不写 index.php )#about

href="https://www.example.com/#about"

你可以在大多数服务器上用/ (root) 替换index.html的链接,它会工作得很好。

<li><a href="/">HOME</a></li>

要删除#hash ,您可以使用事件侦听器来检测它的更改。

function removeHash() {
  // Option 1: This will only remove the part after "#", i.e. hash value
  window.location.hash = "";

  // Option 2: This will split the URL by "#" and use the part before it
  history.pushState(null, null, window.location.href.split("#")[0]);
}

// Remove hash whenever hash is changed
window.addEventListener('hashchange', removeHash, false);

// Run it once when page loads
removeHash();

注意:不要同时使用上述两个选项! 否则就会变成无限递归。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM