繁体   English   中英

锚链接以在页面上打开特定的选项卡(cbpFWTabs)

[英]Anchor Link to open a specific Tab on a Page (cbpFWTabs)

我一直在使用codrops Tab Styles Inspiration中的标签,并且需要能够打开url上的特定标签。

基本上,如果我想打开tab3,则可以链接www.google.com/index#tab3。

这是我的代码:

<div class="tabs tabs-style-topline">
<nav>
<ul>
<li><a href="#section-topline-1"><span>Overview</span></a></li>
<li><a href="#section-topline-2"><span>Register</span></a></li>
<li><a href="#section-topline-3"><span>Exhibitors</span></a></li>
</ul>
</nav>

<div class="content-wrap">
<section id="section-topline-1">Test 1</section>
<section id="section-topline-2">Test 2</section>
<section id="section-topline-3">Test 3</section>
</div><!-- /content -->
</div><!-- /tabs -->

这是javascript:

;( function( window ) {

'use strict';

function extend( a, b ) {
    for( var key in b ) { 
        if( b.hasOwnProperty( key ) ) {
            a[key] = b[key];
        }
    }
    return a;
}

function CBPFWTabs( el, options ) {
    this.el = el;
    this.options = extend( {}, this.options );
    extend( this.options, options );
    this._init();
}

CBPFWTabs.prototype.options = {
    start : 0
};

CBPFWTabs.prototype._init = function() {
    // tabs elems
    this.tabs = [].slice.call( this.el.querySelectorAll( 'nav > ul > li' )         );
    // content items
    this.items = [].slice.call( this.el.querySelectorAll( '.content-wrap >  section' ) );
    // current index
    this.current = -1;
    // show current content item
    this._show();
    // init events
    this._initEvents();
};

CBPFWTabs.prototype._initEvents = function() {
    var self = this;
    this.tabs.forEach( function( tab, idx ) {
        tab.addEventListener( 'click', function( ev ) {
            ev.preventDefault();
            self._show( idx );
        } );
    } );
};

CBPFWTabs.prototype._show = function( idx ) {
    if( this.current >= 0 ) {
        this.tabs[ this.current ].className = this.items[ this.current   ].className = '';
    }
    // change current
    this.current = idx != undefined ? idx : this.options.start >= 0 &&         this.options.start < this.items.length ? this.options.start : 0;
    this.tabs[ this.current ].className = 'tab-current';
    this.items[ this.current ].className = 'content-current';
};

// add to global namespace
window.CBPFWTabs = CBPFWTabs;

})( window );

抱歉,我不是一个jQuery专家,并且整日都在努力寻找解决方案,并开了一个账户问这个问题。 在此先感谢您的帮助。

也许只听window.hashchange事件就可以了, nav > li > a !上没有单击处理程序。 jQuery方式:

$(function(){
    $(window).on('hashchange', function(e) {
        var hash = window.location.hash;

        // first reset classes
        $('nav li').removeClass('tab-current');
        $('.content-wrap section').removeClass('content-current');  

        $('nav li a[href="' + hash + '"]').parents('li').addClass('tab-current');
        $('section[id="' + hash.replace('#', '') + '"]').addClass('content-current');
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM