Preventing scroll when using URI hash to identify tab

前端 未结 8 1836
陌清茗
陌清茗 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:44

    As others have mentioned the code from @Mottie might have once worked on older versions of jQuery UI, but this has definitely stopped working. The jQuery UI Tabs api has changed quite a bit since that was written so here is an updated version that works with at least jQuery 1.10.2

    Demo here: http://jsfiddle.net/xsx5u5g2/

    var $tabs = $("#tabs");
    $tabs.tabs({
      create: function(event, ui) {
        // Adjust hashes to not affect URL when clicked.
        var widget = $tabs.data("uiTabs");
        widget.panels.each(function(i){
          this.id = "uiTab_" + this.id; // Prepend a custom string to tab id.
          widget.anchors[i].hash = "#" + this.id;
          $(widget.tabs[i]).attr("aria-controls", this.id);
        });
      },
      activate: function(event, ui) {
        // Add the original "clean" tab id to the URL hash.
        window.location.hash = ui.newPanel.attr("id").replace("uiTab_", "");
      },
    });
    
    0 讨论(0)
  • 2020-12-11 16:44

    I just added the following to my javascript:

        $('#tabs').tabs();
        // Direct links to the tabs, e.g. /my-page#tab-id can cause browsers
        // to scroll down to half-way down the page, which is ugly. We override that here.
        // (This can cause a brief FOUC effect where the page first displays then scrolls up)
        window.scrollTop = '0';
        window.scrollTo(0,0);
    

    In MSIE, I get a brief FOUC effect as the page loads scrolled part-way-down, then flicks to the top.

    In Firefox, this works fine without any visible FOUC.

    In Chrome, this doesn't work at all -- see scrollTop does not work in Chrome, nor do suggested workarounds

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