直接链接到CSS选项卡



我正在想办法给某人一个直接链接到我页面上的CSS选项卡,但给他们pagename.html#tab2是行不通的。如果可以在没有脚本的情况下做到这一点,那将是最好的,但在这一点上,我对任何事情都持开放态度。顺便说一句,请随意撕毁我的代码!我只是在学习如何做到这一点,所以它可能没有应有的效率!谢谢

/* Tabs */
input  /*hide radio buttons */
{
display: none;
}
input+label  /* show labels in line */
{
display: inline-block;
font-size: 1.3em;
}
input~.tab  /* show contents only for selected tab */
{
display: none;
}
#tab1:checked~.tab.content1,
#tab2:checked~.tab.content2 {
display: block;
}
input+label {
border: 1px solid #999;
background: #101010;
padding: 4px 12px;
border-radius: 6px 6px 0 0;
position: relative;
top: 1px;
}
input+label:hover {
background: #212121;
}
input:checked+label {
background: transparent;
border-bottom: 2px solid #292929;
}
input~.tab {
border-top: 1px solid #999;
padding: 12px;
}
<div style="background-color: #292929;color: #b2b2b2;line-height: 1.5em;font-family: Mulish,sans-serif;">
<input type="radio" name="tabs" id="tab1" checked="checked" />
<label for="tab1">Tab 1</label>
<input type="radio" name="tabs" id="tab2" />
<label for="tab2">Tab 2</label>
<div class="tab content1">
<p>Tab content 1</p>
</div>
<div class="tab content2">
<p>Tab content 2</p>
</div>
</div>

如果指定

<input type="radio" name="tabs" id="tab1" checked />

则在加载页面时,默认情况下会选中此单选按钮。如果你想检查另一个选项卡,你可以从URL中获取哈希,然后像一样以编程方式检查它

<script>
// this will be #tag2 in your case
let hash = document.location.hash;
// remove the hash sign
hash = hash.slice(1, hash.length);
let tab = document.getElementById( hash );
// check the required input element
tab.setAttribute('checked', 'checked');
</script>

在加载输入元素之后,您将希望在接近身体末端的位置包含此脚本。

使用

scrollIntoView()

检查一下这份文件:https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

我希望这能帮助

最新更新