html – 使用文档片段的锚元素的CSS选择器

html – 使用文档片段的锚元素的CSS选择器,第1张

概述请考虑以下示例代码 <body> <nav> <a href="#s1">First Section</a> <a href="#s2">Section 2</a> </nav> <main> <section id="s1"> <p>Example paragraph <p>P 请考虑以下示例代码

<body>    <nav>        <a href="#s1">First Section</a>        <a href="#s2">Section 2</a>    </nav>    <main>        <section ID="s1">            <p>Example paragraph            <p>Paragraph 2        </section>        <section ID="s2">            <p>Example paragraph            <p>Paragraph 2        </section>    </main></body>

我可以选择所选的部分

section {    background: #fff;}section:target {    background: #f00;}

但是我希望仅使用HTML / CSS来定位选择它的a,我可以想象它就像

a[href=:target] {    Font-weight: bold;  }

要么

a:target(href) {    Font-weight: bold;}

我能想到的唯一解决方案是

HTML:

<body>    <div ID="s1"><div ID="s2">        <nav>            <a href="#s1">First Section</a>            <a href="#s2">Section 2</a>        </nav>        <main>            <section name="s1">                <p>Example paragraph                <p>Paragraph 2            </section>            <section name="s2">                <p>Example paragraph                <p>Paragraph 2            </section>        </main>    </div></div></body>

CSS:

#s1:target a[href="#s1"],#s2:target a[href="#s2"] {    Font-weight: bold;}section {    background: #fff;}#s1:target section[name="s1"],#s2:target section[name="s2"] {    background: #f00;}

但是,我不喜欢这样,因为它引入了不必要的元素(目标的div).

没有JavaScript,有没有一个干净的方法来做到这一点?

解决方法 虽然:target伪类用于匹配命名锚或具有与当前URL片段对应的ID的元素,但CSS不提供用于匹配指向当前URL片段的链接的选择器.

没有JavaScript,没有干净的方法可以做到这一点.我更倾向于使用JavaScript而不是为了容纳CSS而使用非语义元素和无效属性来污染标记(部分元素不能具有名称属性).

hashchange事件是well-supported,所以如果你能负担得起,只需要监听那个事件并在正确的元素上切换一个类:

var navlinks = document.querySelectorAll('nav > a');window.onhashchange = function() {    for (var i = 0; i < navlinks.length; i++) {        if (navlinks[i].href.match(/(#.*)/)[1] == window.location.hash) {            navlinks[i].classname = 'selected';        } else {            navlinks[i].classname = '';        }    }};
var navlinks = document.querySelectorAll('nav > a');window.onhashchange = function() {    for (var i = 0; i < navlinks.length; i++) {        if (navlinks[i].href.match(/(#.*)/)[1] == window.location.hash) {            navlinks[i].classname = 'selected';        } else {            navlinks[i].classname = '';        }    }};
section {    background: #fff;}section:target {    background: #f00;}a.selected {    Font-weight: bold;}
<nav>    <a href="#s1">First Section</a>    <a href="#s2">Section 2</a></nav><main>    <section ID="s1">        <p>Example paragraph        <p>Paragraph 2    </section>    <section ID="s2">        <p>Example paragraph        <p>Paragraph 2    </section></main>
总结

以上是内存溢出为你收集整理的html – 使用文档片段的锚元素的CSS选择器全部内容,希望文章能够帮你解决html – 使用文档片段的锚元素的CSS选择器所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1061222.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存