如何使用w3c选项卡样式链接到特定选项卡

时间:2017-05-10 18:07:10

标签: javascript html css hyperlink tabs

我正在建立一个网站,并希望将标签式界面与侧边栏菜单相结合,侧边栏子菜单对应于每个标签。我修改了W3schools的JavaScript标签供我使用,但我无法弄清楚如何直接链接其中一个标签。我发现的每个指南似乎都使用<li>来创建选项卡式界面,而W3C建议使用<button class="tablinks" id="tab1" onclick="openCity(event, 'tab1')">Tab 1</button>。这是我的代码:

<div class="tabbedbox">
    <div class="tab">
        <button class="tablinks" id="tab1" onclick="openCity(event, 'first')">First</button>
        <button class="tablinks" id="tab2" onclick="openCity(event, 'Second')">Second</button>
        <button class="tablinks" id="tab3" onclick="openCity(event, 'Third')">Third</button>
        <button class="tablinks" id="tab4" onclick="openCity(event, 'Fourth')">Fourth</button>
        <button class="tablinks" id="tab5" onclick="openCity(event, 'Fifth')">Fifth</button>
    </div>

    <div id="First" class="tabcontent">
        Tab Text
    </div>

    <div id="Second" class="tabcontent">
        Tab Text
    </div>

    <div id="Third" class="tabcontent">
        Tab Text
    </div>

    <div id="Fourth" class="tabcontent">
        Tab Text
    </div>

    <div id="Fifth" class="tabcontent">
        Tab Text
    </div>
</div>

这是我的JS:

function openCity(evt, cityName) {
    // Declare all variables
    var i, tabcontent, tablinks;

    // Get all elements with class="tabcontent" and hide them
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }

    // Get all elements with class="tablinks" and remove the class "active"
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    // Show the current tab, and add an "active" class to the button that opened the tab
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
    openCity.defaultOptions = {
        "param": "tab"
    }
}

我需要使用哪些代码才能将每个标签与https://www.example.com/tabpage#tab1类型链接相关联?

1 个答案:

答案 0 :(得分:0)

:target伪类可能是您的正确选择。

  

目标CSS伪类表示一个唯一的元素(目标元素),其id与URL的片段匹配。

您可以像下面这样使用它:

.tabcontent{
  display:none;
}
.tabcontent:target{
  display:block;
}
<div class="tabbedbox">
    <div class="tab">
        <button class="tablinks" id="tab1">First</button>
        <button class="tablinks" id="tab2">Second</button>
        <button class="tablinks" id="tab3">Third</button>
    </div>
    <div id="First" class="tabcontent">
       First Tab Text
    </div>
    <div id="Second" class="tabcontent">
       Second Tab Text
    </div>
    <div id="Third" class="tabcontent">
      Third Tab Text
    </div>
</div>
<br>
<a href="#First">goto first tab content via #First hash</a>

现在的javascript并不完全兼容,但我认为从这一点开始,你应该可以让它自己运作。