【问题标题】:Linking directly to a CSS tab直接链接到 CSS 选项卡
【发布时间】:2022-01-22 07:20:44
【问题描述】:

我试图弄清楚如何给某人一个指向我页面上的 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>

【问题讨论】:

  • :target 之类的东西可能会起作用。
  • 我不这么认为,我知道的通过css无法设置checked属性。也许您可以根据散列设置页面样式,但随后您将失去输入按钮的功能。我想你在这里需要一个脚本。我会制定一个答案。

标签: html css hyperlink tabs


【解决方案1】:

使用

scrollIntoView()

查看此文档:https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

我希望这会有所帮助?

【讨论】:

    【解决方案2】:

    如果你指定

    <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>
    

    您将希望在您的正文末尾附近包含此脚本,在输入元素加载之后。

    【讨论】:

    • 谢谢,@mrmonsieur!所以我添加了它,然后去了 pagename.com#tab2 并没有用。我是否使用了不正确的语法?
    • 对不起,我不精确,懒得验证,但现在我有
    • 编辑后的答案对我有用,并且做了它应该做的事情
    • 非常感谢!那行得通!我会赞成它,但我还没有声誉。 :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2016-06-22
    • 2014-06-15
    相关资源
    最近更新 更多