簡體   English   中英

根據網址設置活動標簽

[英]Setting active tab based on url

我有一個簡單的選項卡式界面,可在隱藏的div之間切換,並在單擊時在適當的選項卡上設置活動狀態。

當某人訪問選項卡的url時,它僅顯示該選項卡的內容,這很好。

如果您直接訪問了該URL,我還需要設置該選項卡的活動狀態。

我有url,例如abc.com/index.html#gallery、abc.com/index.html#recipes等。

因此,如果您訪問abc.com/index.html#recipes-“食譜”標簽將突出顯示。

我的代碼如下,在此先感謝您的任何建議!

    $(function () {
var app = {
        vars: {
            gallery: $('#gallery'),
            tabContent: $('.tabs .tabContent'),
            nav: $('.tabs nav a')
        },
        events: function () {
            //tabs
            app.vars.nav.on('click', function (e) {
                var thisHash = $(this).attr('href');
                app.setHash(thisHash);
                e.preventDefault();
                $('nav a').removeClass('active');
                $(this).addClass('active');
            });

            //hashchange
            $(window).on('hashchange', function() {
                app.checkHash();
            });

        },
        checkHash: function () {
            var hash = app.getHash();

            if (hash == '') {
                app.vars.tabContent.hide();
                app.vars.gallery.show();
            } else {
                app.goTo(hash);
            }

        },
        getHash: function () {
            return window.location.hash;
        },
        setHash: function (id) {
            window.location.hash = id;
        },
        goTo: function (id) {
            app.vars.tabContent.hide();
            $(id).fadeIn();
        }
    }
app.events();
app.checkHash();


});

您需要修改goTo函數以在相關選項卡上設置active類。 嘗試這個:

goTo: function (id) {
    app.vars.tabContent.hide();
    $(id).fadeIn();
    $('nav a[href="' + id + '"]').addClass('active').siblings().removeClass('active');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM