How to set Default tab using target?

血红的双手。 提交于 2019-12-12 01:09:38

问题


i am trying to build a simple tabbed interface and i am stalled. All works fine except, when cant seem to find a way to set default tab when loaded.

I would like to see when page loads, i want the tab-1 to be visible. Can it be done using pure css, if not for jquery

Here is the code.

<div class='tabs'>
                    <ul class='horizontal'>
                        <li><a href="#tab-1">General</a></li>
                        <li><a href="#tab-2">Showcase Box</a></li>

                    </ul>
<div id='tab-1' class="tab"> Tab1  Content here </div>                  <div id='tab-1' class="tab"> Tab 2 Content here </div>

CSS

.tabs div:not(:target) { display:none; }

.tabs div:target { display:block; }

回答1:


I dont know if you could do this with css alone, but in javascript you can use window.location.hash to know if a hash is specified or not, if not it will redirect you to #tab-1.

Try this:

    <style>
    .tabs div:not(:target) { display:none; }
    .tabs div:target { display:block; } 
    </style>


    <div class='tabs'>
        <ul class='horizontal'>
            <li><a href="#tab-1">General</a></li>
            <li><a href="#tab-2">Showcase Box</a></li>
        </ul>
        <div id='tab-1' class="tab"> Tab1  Content here </div>                  
        <div id='tab-2' class="tab"> Tab 2 Content here </div>
    </div>

    <script>
    (function(){
        if (window.location.hash) {
            window.location.hash;
        } else {
            window.location.hash = '#tab-1';
        };
    })();
    </script>


来源:https://stackoverflow.com/questions/21362924/how-to-set-default-tab-using-target

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!