Twitter Bootstrap - Tabs - URL doesn't change

前端 未结 15 1538
长情又很酷
长情又很酷 2020-11-28 18:53

I\'m using Twitter Bootstrap and its \"tabs\".

I have the following code:

相关标签:
15条回答
  • 2020-11-28 19:03

    For those using Ruby on Rails or any other server side script, you will want to use the anchor option on paths. This is because once the page loads, it does not have the URL hash available. You will want to supply the correct tab via your link or form submission.

    <%= form_for @foo, url: foo_path(@foo, anchor: dom_id(foo)) do |f| %>
    # Or
    <%= link_to 'Foo', foo_path(@foo, anchor: dom_id(foo)) %>
    

    If you are using a prefix to prevent the window from jumping to the id:

    <%= form_for @foo, url: foo_path(@foo, anchor: "bar_#{dom_id(foo)}") do |f| %>
    

    Then you CoffeeScript:

      hash = document.location.hash
      prefix = 'bar_'
      $('.nav-tabs a[href=' + hash.replace(prefix, '') + ']').tab 'show' if hash
      $('.nav-tabs a').on 'shown.bs.tab', (e) ->
        window.location.hash = e.target.hash.replace '#', '#' + prefix
    

    Or JavaScript:

    var hash, prefix;
    
    hash = document.location.hash;
    prefix = 'bar_';
    
    if (hash) {
      $('.nav-tabs a[href=' + hash.replace(prefix, '') + ']').tab('show');
    }
    
    $('.nav-tabs a').on('shown.bs.tab', function(e) {
      window.location.hash = e.target.hash.replace('#', '#' + prefix);
    });
    

    This should work in Bootstrap 3.

    0 讨论(0)
  • 2020-11-28 19:06

    Here's an option using history.pushState so that you can use your browser history to go back to a previous tab

      $(document).ready(function() {
      // add a hash to the URL when the user clicks on a tab
      $('a[data-toggle="tab"]').on('click', function(e) {
        history.pushState(null, null, $(this).attr('href'));
      });
      // navigate to a tab when the history changes
      window.addEventListener("popstate", function(e) {
        var activeTab = $('[href=' + location.hash + ']');
        if (activeTab.length) {
          activeTab.tab('show');
        } else {
          $('.nav-tabs a:first').tab('show');
        }
      });
    });
    
    0 讨论(0)
  • 2020-11-28 19:07

    This also fixes an extremely obscure tab a href not firing when using jquery and bootstrap

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
    
    <script type="text/javascript">
    $('.nav-tabs a').click(function (e) {
        // No e.preventDefault() here.
        $(this).tab('show');
    });
    </script>
    
    <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
    
    0 讨论(0)
  • 2020-11-28 19:09

    There are three components necessary for a complete solution:

    1. Show the correct tab when the page is loaded if there is a hash in the URL.
    2. Changing the hash in the URL when the tab is changed.
    3. Change the tab when the hash changes in the URL (back / forward buttons), and make sure the first tab is cycled correctly.

    I don't think any of the comments here, nor the accepted answer, handle all of these scenarios.

    As there's quite a bit involved, I think it's neatest as a small jQuery plugin: https://github.com/aidanlister/jquery-stickytabs

    You can call the plugin like so:

    $('.nav-tabs').stickyTabs();
    

    I've made a blog post for this, http://aidanlister.com/2014/03/persisting-the-tab-state-in-bootstrap/

    0 讨论(0)
  • 2020-11-28 19:12

    Same problem with CakePHP with Bootstrap 3 Tabs, plus when i send with external URL and anchor, it jumps to the section losing my menu, after review many solutions made this...

    thanks to: http://ck.kennt-wayne.de/2012/dec/twitter-bootstrap-how-to-fix-tabs

    $(document).ready(function()
     {  
    //Redirecciona al tab, usando un prefijo al cargar por primera vez, al usar redirect en cake #_Pagos    
    //Redirecciona al tab, usando #Pagos
    /* Automagically jump on good tab based on anchor; for page reloads or links */
     if(location.hash) 
      {
         $('a[href=' + location.hash + ']').tab('show');         
      }
    
    
    //Para evitar el bajar al nivel del tab, (al mostrarse el tab subimos)
    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) 
    {
        location.hash = $(e.target).attr('href').substr(1);
        scrollTo(0,0);      
    });
    
    
    
    //Actualiza el URL con el anchor o ancla del tab al darle clic
     /* Update hash based on tab, basically restores browser default behavior to
     fix bootstrap tabs */
    $(document.body).on("click", "a[data-toggle]", function(event) 
      {
        location.hash = this.getAttribute("href");
      });
    
    
    //Redirecciona al tab, al usar los botones de regresar y avanzar del navegador.
    /* on history back activate the tab of the location hash if exists or the default tab if no hash exists */   
    $(window).on('popstate', function() 
    {
      //Si se accesa al menu, se regresa al tab del perfil (activo default), fixed conflict with menu
      //var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");
      var anchor = location.hash;
      $('a[href=' + anchor + ']').tab('show');
    
    });   
    
    });//Fin OnReady
    
    0 讨论(0)
  • 2020-11-28 19:14

    I am using Bootstrap 3.3.* and none of the above solution helped me, even marked as answer one. I just added below script and worked.

    $(function(){
        var hash = document.location.hash;
        if (hash) {
           $('.navbar-nav a[href="' + hash + '"]').tab('show');
        }
        $('a[data-toggle="tab"]').on('click', function (e) {
           history.pushState(null, null, $(this).attr('href'));
        });
    });
    

    Hope this helps you.

    0 讨论(0)
提交回复
热议问题