【问题标题】:Change url for bookmarking when clicking href `#`单击href`#`时更改书签的url
【发布时间】:2021-05-28 15:17:24
【问题描述】:

我通过这次点击在页面内移动

<a class="nav-link" href="#news">News</a>

<section id="news" class="works">

如果我点击链接,我可以移动到该部分。

或直接输入example.com/#news 即可。

但在第一种方法中,网址不会更改为example.com/#news,而是example.com/

所以书签是不可能的。

移动herf #时如何更改网址?

发现js有干扰,请问可以加一句改url吗??

on('click', '#navbar .nav-link', function(e) {
    let section = select(this.hash)
  
    if (section) {
      e.preventDefault()
      
      let navbar = select('#navbar')
      let header = select('#header')
      
      let sections = select('section', true)
      let navlinks = select('#navbar .nav-link', true)
 
      navlinks.forEach((item) => {
        item.classList.remove('active')
      })

      this.classList.add('active')

      if (navbar.classList.contains('navbar-mobile')) {
        navbar.classList.remove('navbar-mobile')
        let navbarToggle = select('.mobile-nav-toggle')
        navbarToggle.classList.toggle('bi-list')
        navbarToggle.classList.toggle('bi-x')
      }

      if (this.hash == '#header') {
        header.classList.remove('header-top')
        sections.forEach((item) => {
          item.classList.remove('section-show')
        })
        return;
      }

      if (!header.classList.contains('header-top')) {
        header.classList.add('header-top')
        setTimeout(function() {
          sections.forEach((item) => {
            item.classList.remove('section-show')
          })
          section.classList.add('section-show')

        }, 350);
      } else {
        sections.forEach((item) => {
          item.classList.remove('section-show')
        })
        section.classList.add('section-show')
      }

      scrollto(this.hash)
    }
  }, true)

【问题讨论】:

  • "但在第一种方法中,url 不会更改为 example.com/#news 它是 example.com/" — 其他条件相同:确实如此。也许你有一些 JS 干扰。
  • 我发现JS在干扰。我一直很困惑。所以我更新了问题。
  • 你可以加location.hash='this.hash'
  • 对不起,有一个错字!更正:location.hash=this.hash - 就在scrollto(this.hash)之后

标签: javascript html


【解决方案1】:

也许你可以考虑在onclick事件中调用history.replaceState()函数来改变浏览器中的url?

【讨论】:

    猜你喜欢
    • 2022-11-16
    • 2012-04-18
    • 1970-01-01
    • 2011-05-20
    • 2021-08-26
    • 1970-01-01
    • 2013-11-16
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多