programing

Twitter 부트스트랩 탭: 페이지 새로고침 또는 하이퍼링크의 특정 탭으로 이동

nicescript 2022. 9. 30. 13:32
반응형

Twitter 부트스트랩 탭: 페이지 새로고침 또는 하이퍼링크의 특정 탭으로 이동

저는 Twitter의 Bootstrap Framework와 그들의 Bootstrap Tabs JS를 사용하는 웹 페이지를 개발하고 있습니다.몇 가지 사소한 문제를 제외하고는 정상적으로 동작합니다.그 중 하나는 외부 링크에서 특정 탭으로 직접 이동하는 방법을 모른다는 것입니다.예를 들어 다음과 같습니다.

<a href="facility.php#home">Home</a>
<a href="facility.php#notes">Notes</a>

외부 페이지에서 링크를 클릭하면 홈 탭과 메모 탭으로 이동합니다.

조금 늦었을지도 모르지만, 이 문제에 대한 저의 해결 방법이 있습니다.하지만 다른 사람에게 도움이 될 수도 있습니다.

// Javascript to enable link to tab
var hash = location.hash.replace(/^#/, '');  // ^ means starting, meaning only match the first hash
if (hash) {
    $('.nav-tabs a[href="#' + hash + '"]').tab('show');
} 

// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
})

갱신하다

의 는, 「3」을합니다..on('shown', ...)로로 합니다..on('shown.bs.tab', ....)


이는 @dubbe 응답과 이 SO가 받아들인 답변을 기반으로 합니다.다음 문제를 처리합니다.window.scrollTo(0,0)올바르게 동작하지 않는다.문제는 표시된 탭의 URL 해시를 바꾸면 브라우저가 해당 해시로 스크롤된다는 것입니다.이치노합니다.

// Javascript to enable link to tab
var hash = document.location.hash;
var prefix = "tab_";
if (hash) {
    $('.nav-tabs a[href="'+hash.replace(prefix,"")+'"]').tab('show');
} 

// Change hash for page-reload
$('.nav-tabs a').on('shown', function (e) {
    window.location.hash = e.target.hash.replace("#", "#" + prefix);
});

사용 예

id="mytab"인 탭 탭이 있는 경우 링크를 다음과 같이 저장해야 합니다.

<a href="yoursite.com/#tab_mytab">Go to Specific Tab </a>

하면 할 수 요.click이벤트를 표시합니다.「이것들」은 다음과 같습니다.

$(document).ready(function(){

  if(window.location.hash != "") {
      $('a[href="' + window.location.hash + '"]').click()
  }

});

이것은 스크롤을 방지하는 더브 솔루션의 개선된 구현입니다.

// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
    $('.nav-tabs a[href="#'+url.split('#')[1]+'"]').tab('show') ;
} 

// With HTML5 history API, we can easily prevent scrolling!
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    if(history.pushState) {
        history.pushState(null, null, e.target.hash); 
    } else {
        window.location.hash = e.target.hash; //Polyfill for old browsers
    }
})

제공된 JavaScript 솔루션이 작동할 수 있지만, 저는 추가 JavaScript는 필요 없지만 귀하의 관점에서 논리를 필요로 하는 약간 다른 방법을 사용하였습니다.다음과 같은 표준 URL 매개 변수를 사용하여 링크를 만듭니다.

<a href = "http://link.to.yourpage?activeTab=home">My Link</a>

다음 activeTab에 '쓰면 .<li>

의사 코드(사용하는 언어로 적절히 실장).이 예에서 파라미터가 제공되지 않는 경우 'home' 탭을 기본 활성화로 설정합니다.

$activetabhome = (params.activeTab is null or params.activeTab == 'home') ? 'class="active"' : '';
$activetabprofile = (params.activeTab == 'profile') ? 'class="active"' : '';

<li $activetabhome><a href="#home">Home</a></li>
<li $activetabprofile><a href="#profile">Profile</a></li>

나는 만약을 그다지 좋아하지 않기 때문에, 보다 간단한 방법을 택했다.

$(document).ready(function(event) {
    $('ul.nav.nav-tabs a:first').tab('show'); // Select first tab
    $('ul.nav.nav-tabs a[href="'+ window.location.hash+ '"]').tab('show'); // Select tab by name if provided in location hash
    $('ul.nav.nav-tabs a[data-toggle="tab"]').on('shown', function (event) {    // Update the location hash to current tab
        window.location.hash= event.target.hash;
    })
});
  1. 기본 탭(일반적으로 첫 번째)을 선택합니다.
  2. 탭으로 전환합니다(이러한 요소가 실제로 존재하는 경우 jQuery가 처리하도록 합니다).잘못된 해시가 지정되면 아무 일도 일어나지 않습니다.
  3. [선택사항] 수동으로 다른 탭을 선택한 경우 해시를 업데이트합니다.

요청된 해시에 대한 스크롤은 다루지 않습니다만, 그렇게 해야 합니까?

부트스트랩3의 경우:

$('.nav-tabs a[href="#' + tabID + '"]').tab('show');

https://jsfiddle.net/DTcHh/6638/

이는 Bootstrap 3에서 동작하며 Garcia WebDev의 답변도 통합함으로써 dubbe와 flynfish의 2가지 상위 답변을 개선합니다(해시 후 URL 파라미터가 허용되며 Github 문제 트래커의 Bootstrap 작성자로부터 직접 수신됩니다).

// Javascript to enable link to tab
var hash = document.location.hash;
var prefix = "tab_";

if (hash) {
    hash = hash.replace(prefix,'');
    var hashPieces = hash.split('?');
    activeTab = $('.nav-tabs a[href=' + hashPieces[0] + ']');
    activeTab && activeTab.tab('show');
} 

// Change hash for page-reload
$('.nav-tabs a').on('shown', function (e) {
    window.location.hash = e.target.hash.replace("#", "#" + prefix);
});

Demircan Celebi 솔루션을 기반으로 합니다.서버에서 페이지를 새로고침할 필요 없이 URL을 수정할 때 탭을 열고 탭을 열 수 있도록 하고 싶었습니다.

<script type="text/javascript">
    $(function() {
        openTabHash(); // for the initial page load
        window.addEventListener("hashchange", openTabHash, false); // for later changes to url
    });


    function openTabHash()
    {
        console.log('openTabHash');
        // Javascript to enable link to tab
        var url = document.location.toString();
        if (url.match('#')) {
            $('.nav-tabs a[href="#'+url.split('#')[1]+'"]').tab('show') ;
        } 

        // With HTML5 history API, we can easily prevent scrolling!
        $('.nav-tabs a').on('shown.bs.tab', function (e) {
            if(history.pushState) {
                history.pushState(null, null, e.target.hash); 
            } else {
                window.location.hash = e.target.hash; //Polyfill for old browsers
            }
        })
    }
</script>

이 코드는 #해시에 따라 오른쪽 탭을 선택하고 탭을 클릭하면 오른쪽 #해시를 추가합니다.(이것은 jquery를 사용합니다)

Coffeescript:

$(document).ready ->
    if location.hash != ''
        $('a[href="'+location.hash+'"]').tab('show')

    $('a[data-toggle="tab"]').on 'shown', (e) ->
        location.hash = $(e.target).attr('href').substr(1)

또는 JS:

$(document).ready(function() {
    if (location.hash !== '') $('a[href="' + location.hash + '"]').tab('show');
    return $('a[data-toggle="tab"]').on('shown', function(e) {
      return location.hash = $(e.target).attr('href').substr(1);
    });
});
$(function(){
  var hash = window.location.hash;
  hash && $('ul.nav a[href="' + hash + '"]').tab('show');
});

http://github.com/twitter/bootstrap/issues/2415#issuecomment-4450768의 이 코드는 나에게 완벽하게 작동했다.

@flynfish + @Ztyx 솔루션을 네스트된 탭에 사용합니다.

    handleTabLinks();

    function handleTabLinks() {
        if(window.location.hash == '') {
            window.location.hash = window.location.hash + '#_';
        }
        var hash = window.location.hash.split('#')[1];
        var prefix = '_';
        var hpieces = hash.split('/');
        for (var i=0;i<hpieces.length;i++) {
            var domelid = hpieces[i].replace(prefix,'');
            var domitem = $('a[href=#' + domelid + '][data-toggle=tab]');
            if (domitem.length > 0) {
                domitem.tab('show');
            }
        }
        $('a[data-toggle=tab]').on('shown', function (e) {
            if ($(this).hasClass('nested')) {
                var nested = window.location.hash.split('/');
                window.location.hash = nested[0] + '/' + e.target.hash.split('#')[1];
            } else {
                window.location.hash = e.target.hash.replace('#', '#' + prefix);
            }
        });
    }

아이들은 수업을 받아야 한다="반복"

다음 코드의 가용성에 따라 URL 해시 또는 localStorage를 사용하는 솔루션을 생각해냈습니다.

$(function(){
    $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    })

    var hash = window.location.hash;
    var activeTab = localStorage.getItem('activeTab');

    if(hash){
          $('#project-tabs  a[href="' + hash + '"]').tab('show');   
    }else if (activeTab){
        $('#project-tabs a[href="' + activeTab + '"]').tab('show');
    }
});

Bootstrap 작성자가 GitHub의 문제 트래커에 제공한 코드를 사용할 것을 권장합니다.

var hash = location.hash
  , hashPieces = hash.split('?')
  , activeTab = $('[href=' + hashPieces[0] + ']');
activeTab && activeTab.tab('show');

문제 링크에서 지원을 선택하지 않은 이유에 대한 자세한 내용을 확인할 수 있습니다.

위에서 설명한 몇 가지 방법을 시도하여 다음과 같은 솔루션을 사용할 수 있게 되었습니다.복사하여 에디터에 붙여넣기만 하면 됩니다.테스트하려면 해시를 받은 편지함, 송수신함, url로 변경하고 Enter 키를 누르기만 하면 됩니다.

<html>
    <head>
        <link type='text/css' rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css' />
        <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
    </head>
    <body>
        <div class="container body-content">
            <ul class="nav nav-tabs">
                <li class="active"><a data-toggle="tab" href="#inbox">Inbox</a></li>
                <li><a data-toggle="tab" href="#outbox">Outbox</a></li>
                <li><a data-toggle="tab" href="#compose">Compose</a></li>
            </ul>
            <div class="tab-content">
                <div id="inbox" class="tab-pane fade in active">
                    Inbox Content
                </div>
                <div id="outbox" class="tab-pane fade">
                    Outbox Content
                </div>
                <div id="compose" class="tab-pane fade">
                    Compose Content
                </div>
            </div>
        </div>
        <script>
            $(function () {
                var hash = window.location.hash;
                hash && $('ul.nav a[href="' + hash + '"]').tab('show');
            });
        </script>
    </body>
</html>

이것으로 시간을 절약할 수 있기를 바랍니다.

페이지에 다음 코드를 삽입하기만 하면 됩니다.

$(function(){
  var hash = window.location.hash;
  hash && $('ul.nav a[href="' + hash + '"]').tab('show');

  $('.nav-tabs a').click(function (e) {
    $(this).tab('show');
    var scrollmem = $('body').scrollTop();
    window.location.hash = this.hash;
    $('html,body').scrollTop(scrollmem);
  });
});

이것은 매우 간단한 작업입니다.탭 링크에 ID가 관련되어 있는 경우 href 속성을 취득하여 탭 내용을 표시하는 함수에 전달할 수 있습니다.

<script type="text/javascript">
        jQuery(document).ready(function() {
            var hash = document.location.hash;
            var prefix = "tab_";
            if (hash) {
                var tab = jQuery(hash.replace(prefix,"")).attr('href');
                jQuery('.nav-tabs a[href='+tab+']').tab('show');
            }
        });
        </script>

그런 다음 다음과 같이 해시를 추가할 수 있습니다: #tab_tab1. 해시 자체에서 'tab_' 부분이 삭제되어 nav-tablink(tabid1)의 실제 탭 링크의 ID가 뒤에 배치되므로 URL은 www.mydomain.com/index.php#tab_tabid1과 같습니다.

이것은 나에게 딱 맞기 때문에 다른 사람에게 도움이 되길 바랍니다:-)

다른 사람에게 중요한 경우, 다음 코드는 작고 완벽하게 작동하며 URL에서 단일 해시 값을 가져와 이를 나타냅니다.

<script>
    window.onload = function () {
        let url = document.location.toString();
        let splitHash = url.split("#");
        if (splitHash[1]) {document.getElementById(splitHash[1]).click();}
    };
</script>

ID 를 취득해, 클릭 이벤트를 기동합니다.간단하죠.

이것은 중첩된 탭을 처리하는 솔루션입니다.액티브 탭이 활성화 되는 부모 탭이 있는지 확인하는 기능을 추가했습니다.기능은 다음과 같습니다.

function activateParentTab(tab) {
    $('.tab-pane').each(function() {
        var cur_tab = $(this);
        if ( $(this).find('#' + tab).length > 0 ) {
            $('.nav-tabs a[href=#'+ cur_tab.attr('id') +']').tab('show');
            return false;
        }
    });
}

@flynfish의 솔루션에 근거해, 다음과 같이 불릴 수 있습니다.

var hash = document.location.hash;
var prefix = "";
if (hash) {
    $('.nav-tabs a[href='+hash.replace(prefix,"")+']').tab('show');
    activateParentTab(hash);
} 

// Change hash for page-reload
$('.nav-tabs a').on('shown', function (e) {
    window.location.hash = e.target.hash.replace("#", "#" + prefix);
});

이 솔루션은 현재 나에게는 꽤 효과가 있습니다.이것이 다른 사람에게 도움이 되기를 바랍니다;)

이 기능을 사용하려면 몇 가지 비트를 수정해야 했습니다.부트스트랩3과 jQuery2를 사용하고 있습니다.

// Javascript to enable link to tab
var hash = document.location.hash;
var prefix = "!";
if (hash) {
    hash = hash.replace(prefix,'');
    var hashPieces = hash.split('?');
    activeTab = $('[role="tablist"] a[href=' + hashPieces[0] + ']');
    activeTab && activeTab.tab('show');
}

// Change hash for page-reload
$('[role="tablist"] a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash.replace("#", "#" + prefix);
});

방금 이 문제가 있었는데 여러 탭 수준을 처리해야 했습니다.이 코드는 다소 추악하지만(댓글 참조), 제 역할을 한다.https://gist.github.com/JensRantil/4721860 다른 누군가가 이 코드가 유용하다고 생각하기를 바란다(그리고 더 나은 해결책을 제안할 수 있기를!).

다른 답변의 피어를 조합하여 여러 레벨의 중첩 탭을 열 수 있는 솔루션을 다음에 나타냅니다.

// opens all tabs down to the specified tab
var hash = location.hash.split('?')[0];
if(hash) {
  var $link = $('[href=' + hash + ']');
  var parents = $link.parents('.tab-pane').get();
  $(parents.reverse()).each(function() {
    $('[href=#' + this.id + ']').tab('show') ;
  });
  $link.tab('show');
}

Ajax와의 링크에 대해 이렇게 만듭니다.#!#(예:/test.com#!#test3). 단, 원하는 대로 변경할 수 있습니다.

$(document).ready(function() {

       let hash = document.location.hash;
       let prefix = "!#";

       //change hash url on page reload
       if (hash) {
         $('.nav-tabs a[href=\"'+hash.replace(prefix,"")+'\"]').tab('show');
       } 

       // change hash url on switch tab
       $('.nav-tabs a').on('shown.bs.tab', function (e) {
          window.location.hash = e.target.hash.replace("#", "#" + prefix);
       });
 });

여기 Github의 간단한 페이지 예시

이 스레드가 매우 오래되었다는 것은 알지만, 여기에서는 제 자신의 실장을 종료합니다.

$(function () {
  // some initialization code

  addTabBehavior()
})

// Initialize events and change tab on first page load.
function addTabBehavior() {
  $('.nav-tabs a').on('show.bs.tab', e => {
    window.location.hash = e.target.hash.replace('nav-', '')
  })

  $(window).on('popstate', e => {
    changeTab()
  })

  changeTab()
}

// Change the current tab and URL hash; if don't have any hash
// in URL, so activate the first tab and update the URL hash.
function changeTab() {
  const hash = getUrlHash()

  if (hash) {
    $(`.nav-tabs a[href="#nav-${hash}"]`).tab('show')
  } else {
    $('.nav-tabs a').first().tab('show')
  }
}

// Get the hash from URL. Ex: www.example.com/#tab1
function getUrlHash() {
  return window.location.hash.slice(1)
}

사용하고 있는 것에 주의해 주세요.nav-클래스 프리픽스를 네비게이션링크로 바꿉니다.

Peter의 답변을 바탕으로 https://stackoverflow.com/a/901144/1604205,을 통합하면 JS의 코드는 다음과 같습니다.

<script>
    const params = new Proxy(new URLSearchParams(window.location.search), {
        get: (searchParams, prop) => searchParams.get(prop),
    });
    $activetabhome = (params.activeTab === null || params.activeTab == 'home') ? 'class="active"' : '';
    $activetabprofile = (params.activeTab == 'profile') ? 'class="active"' : '';
</script>
<li $activetabhome><a href="#home">Home</a></li>
<li $activetabprofile><a href="#profile">Profile</a></li>

언급URL : https://stackoverflow.com/questions/7862233/twitter-bootstrap-tabs-go-to-specific-tab-on-page-reload-or-hyperlink

반응형