2014-10-10 42 views
0

我目前正在使用Javascript在包含4個不同製表符的頁面上進行動畫/切換。使用URL參數模擬點擊

我希望能夠定位這些標籤,以便根據URL參數訪問選定的選項卡。

但是,此時從一個標籤切換到另一個標籤的唯一方法是單擊它。

因此,我假設一個簡單的方法是設置頁面的4個不同的URL。例如,

pagename.com#1 
pagename.com#2 
pagename.com#3 
pagename.com#4 

每個數字模擬選項卡上的1點擊到4

我能做到這樣呢?

非常感謝, 傑洛特

回答

1

如上狀態的回答,您可以使用window.location.hash改變哈希值。但是,如果您的選項卡不具備該功能,則活動選項卡不會僅通過添加/更改哈希來更改。什麼,你需要做的就是在你的JavaScript看待當前的哈希值,並確定對應標籤/面板顯示...看看這個例子:

HTML:

<div id="tabs"> 
    <div><a href="#1">Tab 1</a></div> 
    <div><a href="#2">Tab 2</a></div> 
    <div><a href="#3">Tab 3</a></div> 
    <div><a href="#4">Tab 4</a></div> 
</div> 

<div id="panels"> 
    <div id="1">I am a panel 1</div> 
    <div id="2">I am a panel 2</div> 
    <div id="3">I am a panel 3</div> 
    <div id="4">I am a panel 4</div> 
</div> 

CSS:

#tabs > div { 
    display: inline-block; 
} 

#panels > div { 
    display: none; 
} 

JS:

$(document).ready(function() { 
    // if you want the first one shown... 
    window.location.hash = '#1'; 
    // initially check... 
    var h = window.location.hash; 
    var panel = findPanel(h); 
    if (panel) { 
     panelCleanUp() 
     $(panel).show(); 
    } 

    $('#tabs').on('click', 'a', function() { 
     setTimeout(function() { // let the hash update... 
      var hasher = window.location.hash; 
      var panel = findPanel(hasher); 
      if (panel) { 
       panelCleanUp(); 
       $(panel).show(); 
      } 
     }, 0); 
    }); 
}); 


function findPanel(hasher) { 
    return $('#panels ' + hasher)[0]; 
} 

function panelCleanUp() { 
    $('#panels > div').each(function() { 
     $(this).hide(); 
    }); 
} 

See the Fiddle

+0

聽起來正是我需要的!謝謝! 我試圖根據您的示例更新我的頁面,但最終每次都會破壞代碼。 你認爲這樣的基礎是可行的:http://jsfiddle.net/72Lk1tfm/? – Geralt745 2014-10-10 16:03:48

+0

在這裏,我得到它與你的例子...你的主要問題是你忘了包括jquery,所以你的代碼沒有運行... http://jsfiddle.net/72Lk1tfm/1/ – almightyBoognish 2014-10-10 17:21:56

+0

如果你發現這有助於表決/使其成爲您的問題的批准答案! – almightyBoognish 2014-10-10 20:33:51

0

是的!使用window.location.hash

window.location.hash = "1"; // done! 
+0

聽起來像一個很好的計劃!你能否解釋我如何用我的例子來實現它?我一直在W3schools,但我仍然有點困惑... 非常感謝! – Geralt745 2014-10-10 15:03:13

+0

@ Geralt745你把你想要的東西放在'#'後面'#' – 2014-10-10 15:06:29

+0

這樣的事情到達tab2? http://jsfiddle.net/Lqovgexw/ 對不起,我很困惑這個功能的使用.. – Geralt745 2014-10-10 15:20:12