jQuery Mobile Navigation Tabs

前端 未结 6 945
遇见更好的自我
遇见更好的自我 2020-12-25 15:39

I want to have a tab-navigation in my jQuery Mobile project. I know I can use the data-role \'navbar\' but I only want to change the content below that navbar without swipin

6条回答
  •  礼貌的吻别
    2020-12-25 16:04

    You can use the jQuery Mobile navbar styling but use your own click-handler so instead of changing pages the click will just hide/show the proper content on the same page.

    HTML

    
    
    onLoad Content
    Some 'A' Content
    Some 'B' Content

    JAVASCRIPT

    $(document).delegate('[data-role="navbar"] a', 'click', function () {
        $(this).addClass('ui-btn-active');
        $('.content_div').hide();
        $('#' + $(this).attr('data-href')).show();
        return false;//stop default behavior of link
    });
    

    CSS

    .content_div {
        display: none;
    }
    .content_div:first-child {
        display: block;
    }
    

    Here is a jsfiddle of the above code: http://jsfiddle.net/3RJuX/

    NOTE:

    • Each of the links in the navbar have a "data-href" attribute set to the id of the div (or whatever container you want to use) that will be displayed.

    Update

    After 1 year I came back to this answer and noticed that the delegated event handler selector can be optimized a bit to utilize a class rather than an attribute (which is a lot faster of a lookup):

    $(document).delegate('.ui-navbar a', 'click', function () {
        $(this).addClass('ui-btn-active');
        $('.content_div').hide();
        $('#' + $(this).attr('data-href')).show();
    });
    

    Update

    This code can be made to be more modular by using relative selectors rather than absolute ones (like $('.content_div'), as this will select all matching elements in the DOM rather than just ones relative to the button clicked).

    //same selector here
    $(document).delegate('.ui-navbar ul li > a', 'click', function () {
    
        //un-highlight and highlight only the buttons in the same navbar widget
        $(this).closest('.ui-navbar').find('a').removeClass('ui-navbar-btn-active');
    
        //this bit is the same, you could chain it off of the last call by using two `.end()`s
        $(this).addClass('ui-navbar-btn-active');
    
        //this starts the same but then only selects the sibling `.content_div` elements to hide rather than all in the DOM
        $('#' + $(this).attr('data-href')).show().siblings('.content_div').hide();
    });​
    

    This allows you to nest tabs and/or have multiple sets of tabs on a pages or pseudo-pages.

    Some documentation for the "relative selectors" used:

    • .closest() : http://api.jquery.com/closest
    • .siblings() : http://api.jquery.com/siblings

    Here was an example: http://jsfiddle.net/Cfbjv/25/ (It's offline now)

提交回复
热议问题