Javascript Twitter引导选项卡:转到页面重新加载或超链接上的特定选项卡
我正在开发一个网页,在这个网页中我使用了Twitter的引导框架和他们的技术。除了几个小问题外,它工作得很好,其中一个问题是我不知道如何从外部链接直接转到特定选项卡。例如:Javascript Twitter引导选项卡:转到页面重新加载或超链接上的特定选项卡,javascript,html,tabs,twitter-bootstrap,Javascript,Html,Tabs,Twitter Bootstrap,我正在开发一个网页,在这个网页中我使用了Twitter的引导框架和他们的技术。除了几个小问题外,它工作得很好,其中一个问题是我不知道如何从外部链接直接转到特定选项卡。例如: <a href="facility.php#home">Home</a> <a href="facility.php#notes">Notes</a> 单击外部页面的链接时,应分别转到主页选项卡和注释选项卡您可以在相应的选项卡链接上触发单击事件: $(document).
<a href="facility.php#home">Home</a>
<a href="facility.php#notes">Notes</a>
单击外部页面的链接时,应分别转到主页选项卡和注释选项卡您可以在相应的选项卡链接上触发
单击事件:
$(document).ready(function(){
if(window.location.hash != "") {
$('a[href="' + window.location.hash + '"]').click()
}
});
这是我对这个问题的解决方案,也许有点晚了。但它可能会帮助其他人:
// 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;
})
虽然提供的JavaScript解决方案可能有效,但我采用了一种稍微不同的方式,它不需要额外的JavaScript,但在您的视图中确实需要逻辑。使用标准URL参数创建链接,如:
<a href = "http://link.to.yourpage?activeTab=home">My Link</a>
然后您只需检测activeTab的值,在相应的
伪代码(用您的语言相应地实现)。注意:如果本例中未提供任何参数,我已将“主页”选项卡设置为默认活动
$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>
$activetabhome=(params.activeTab为null或params.activeTab=='home')?'class=“active”:“”;
$activetabprofile=(params.activeTab=='profile')?'class=“active”:“”;
更新
对于引导程序3,将.on('显示',…)
更改为.on('显示的.bs.tab',…)
这是基于答案和这个。它处理窗口的问题。滚动到(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>
这段代码对我来说非常有用。我建议您使用Bootstrap作者提供的代码:
您可以在问题的链接上找到有关他们为什么不选择支持该选项的更多信息。此代码根据“哈希”选择正确的选项卡,并在单击选项卡时添加正确的“哈希”。(这使用jquery)
在咖啡脚本中:
$(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);
});
});
下面是我所做的,非常简单,如果您的选项卡链接具有与其关联的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>
jQuery(文档).ready(函数(){
var hash=document.location.hash;
var prefix=“制表符”;
if(散列){
var tab=jQuery(hash.replace(前缀“”).attr('href');
jQuery('.nav tabs a[href='+tab+']').tab('show');
}
});
然后在你的url中,你可以像这样添加散列:#tab#tab1,从散列中删除“tab#”部分,这样导航标签(tabid1)中实际标签链接的ID就放在后面,所以你的url看起来像:www.mydomain.com/index.php#tab#tabid1
这非常适合我,希望它能帮助其他人:-)我刚刚遇到这个问题,但需要处理多个选项卡级别。代码相当难看(请参见注释),但它确实起到了作用:希望其他人会发现它有用(并且可以提出更好的解决方案!)。@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);
}
});
}
// 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');
}
handleTabLinks();
函数handleTabLinks(){
if(window.location.hash==''){
window.location.hash=window.location.hash+'#";
}
var hash=window.location.hash.split(“#”)[1];
变量前缀='";
var hpieces=hash.split('/');
对于(变量i=0;i 0){
“域名”选项卡(“显示”);
}
}
$('a[data toggle=tab]')。在('Showed',函数(e)上{
if($(this).hasClass('nested')){
var nested=window.location.hash.split('/');
window.location.hash=嵌套的[0]+'/'+e.target.hash.split('#')[1];
}否则{
window.location.hash=e.target.hash.replace('#','#'+前缀);
}
});
}
孩子们应该有class=“nested”这是一个改进的实现,可以防止滚动
// 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
}
})
这是我处理嵌套选项卡的解决方案。
我刚刚添加了一个函数来检查活动选项卡是否有要激活的父选项卡。
这就是功能:
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的解决方案):
这个解决方案目前对我来说非常有效。
希望这对其他人有用;) 这在Bootstrap 3中起作用,并通过集成GarciaWebDev的答案(允许在散列之后使用url参数,并且直接从github问题跟踪器上的Bootstrap作者处获得),改进了Duploy和flynfish的两个顶级答案:
我不是“如果……否则”的超级粉丝;所以我采取了一种更简单的方法
$(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;
})
});
选择默认选项卡(通常是第一个)
切换到tab(如果确实存在这样的元素,则让jQuery处理);如果指定了错误的哈希,则不会发生任何事情
[可选]如果手动选择了其他选项卡,则更新哈希
不解决滚动到请求哈希的问题;但是应该吗?我必须修改一些位以使其适合我。
我使用的是bootstrap3和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);
});
对于引导3:
$('.nav-tabs a[href="#' + tabID + '"]').tab('show');
以德米坎·塞莱比的解决方案为基础;我希望在修改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>
$(函数(){
openTabHash();//用于初始页面加载
addEventListener(“hashchange”,openTabHash,false);//用于以后对url的更改
});
函数openTabHash()
{
log('openTabHash');
//J
// 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);
});
$('.nav-tabs a[href="#' + tabID + '"]').tab('show');
<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>
// 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');
}
<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(){
$(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');
}
});
$(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);
});
});
<script>
window.onload = function () {
let url = document.location.toString();
let splitHash = url.split("#");
document.getElementById(splitHash[1]).click();
};
</script>
$(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)
}