Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

前端 未结 24 1942
夕颜
夕颜 2020-11-22 04:57

I\'m developing a web page in which I\'m using Twitter\'s Bootstrap Framework and their Bootstrap Tabs JS. It works great except for a few minor issues, one of which is I do

24条回答
  •  感动是毒
    2020-11-22 05:06

    I know this thread is very old, but I'll leave here my own implementation:

    $(function () {
      // some initialization code
    
      addTabBehavior()
    })
    
    // Initialize events and change tab on first page load.
    function addTabBehavior() {
      $('.nav-tabs a').on('show.bs.tab', e => {
        window.location.hash = e.target.hash.replace('nav-', '')
      })
    
      $(window).on('popstate', e => {
        changeTab()
      })
    
      changeTab()
    }
    
    // Change the current tab and URL hash; if don't have any hash
    // in URL, so activate the first tab and update the URL hash.
    function changeTab() {
      const hash = getUrlHash()
    
      if (hash) {
        $(`.nav-tabs a[href="#nav-${hash}"]`).tab('show')
      } else {
        $('.nav-tabs a').first().tab('show')
      }
    }
    
    // Get the hash from URL. Ex: www.example.com/#tab1
    function getUrlHash() {
      return window.location.hash.slice(1)
    }
    

    Note that I'm using a nav- class prefix to nav links.

提交回复
热议问题