Preventing scroll when using URI hash to identify tab

前端 未结 8 1850
陌清茗
陌清茗 2020-12-11 16:05

I\'m using JQuery UI to make tabs in my application. I needed the tabs to be linkable (direct link that opens the page and selects the correct tab). This is done by using a

8条回答
  •  情深已故
    2020-12-11 16:25

    This may not be the best method, but if you rename all of the ID's after the tabs have been created, then adding a hash with the original ID won't scroll the page. I used this method because even with javascript disabled, the hash will take the user to the correct ID. Here is a demo of the code below:

    $("#tabs").tabs({
        create: function(event, ui) {
            // get tab plugin data
            var tabs = $('#tabs').data('tabs'),
                // tabs.anchors contains all of the tab anchors
                links = tabs.anchors;
            // tabs.panels contains each tab
            tabs.panels.each(function(i){
                // just adding a "mod_" prefix to every ID/hash
                this.id = 'mod_' + this.id;
                links[i].hash = '#' + this.id;
            });
        }
    });
    
    /**
     * Add hash to URL of the current page
     * 
     * http://chwang.blogspot.com/2010/02/jquery-ui-tabs-updating-url-with-hash.html
     * http://stackoverflow.com/questions/570276/changing-location-hash-with-jquery-ui-tabs
     */
    $("#tabs").bind('tabsshow', function(event, ui) {
        // remove the prefix from the ID, so we're showing the original ID in the hash
        window.location.hash = ui.tab.hash.replace('mod_', '');
    });
    

提交回复
热议问题