如何在单击选项卡时显示内容?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (85)

我用HTML和CSS来创建选项卡。单击该按钮,内容区域会添加display:block。

CSS使用简单的代码行显示选项卡内容:

#tab11:checked ~ #ctab11,
#tab12:checked ~ #ctab12 {
    display: block;
}
#tab21:checked ~ #ctab21,
#tab22:checked ~ #ctab22 {
    display: block;
}

我的问题是,如何用JS替换那块CSS?这是因为我想使选项卡动态但保持相同的结构

请看并运行下面的代码,谢谢!

.tabsWrapper {
  margin: 5rem 1rem;
  display: inline-block;
  width: 100%;
}
.tab-content {
    display: none;
    padding: 20px 0 0;
    border-top: 1px solid #ddd;
}
.tab-title {
    display: none;
}
.tab-label {
    display: inline-block;
    margin: 0 0 -1px;
    padding: 15px 25px;
    font-weight: 600;
    text-align: center;
    color: #bbb;
    border: 1px solid transparent;
}
.tab-label:hover {
    color: #888;
    cursor: pointer;
}
.tab-title:checked + label {
    color: #555;
    border: 1px solid #ddd;
    border-top: 2px solid orange;
    border-bottom: 1px solid #fff;
}


/***** Replace this with vanilla JS ******/
#tab11:checked ~ #ctab11,
#tab12:checked ~ #ctab12 {
    display: block;
}

#tab21:checked ~ #ctab21,
#tab22:checked ~ #ctab22 {
    display: block;
}
/***** Replace this with vanilla JS ******/
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>

  <div class="tabsWrapper">

<input id="tab11" type="radio" name="tabs1" class="tab-title" checked>
<label for="tab11" class="tab-label">Title A</label>

<input id="tab12" type="radio" name="tabs1" class="tab-title">
<label for="tab12" class="tab-label">Title B</label>

<section id="ctab11" class="tab-content"> <p>Lorem ipsum dolor sit amet.</p></section>
<section id="ctab12" class="tab-content"> <p>Invidunt menandri duo at, at everti prompta eos.</p></section>

</div>

<div class="tabsWrapper">

<input id="tab21" type="radio" name="tabs2" class="tab-title" checked>
<label for="tab21" class="tab-label">Title A</label>

<input id="tab22" type="radio" name="tabs2" class="tab-title">
<label for="tab22" class="tab-label">Title B</label>

<section id="ctab21" class="tab-content"> <p>Lorem ipsum dolor sit amet.</p></section>
<section id="ctab22" class="tab-content"> <p>Invidunt menandri duo at, at everti prompta eos.</p></section>

</div>
  
</body>
</html>

提问于
用户回答回答于

您可以使用javascript操作样式表

document.getElementById("myDIV").style.display = "none";

参考资料:https://www.w3schools.com/jsref/prop_style_display.asp

扫码关注云+社区

领取腾讯云代金券