样式化锚标签,为页面中当前目标部分("some_url#section")提供链接。

问题描述 投票:0回答:1

在纯CSS的情况下,是否可以选择一个其href属性与当前URL锚匹配的链接,而不需要它的 id 属性,相当于其 href?

例如,如果用户在科 #abc 的主页面 (index.html#abc),我想为那个链接设置一些CSS规则,其上的 href#abc,但只有当用户的URL指向了那个 #abc 节。

比如,下面的HTML。

<a href="#abc">Some link</a>
<a href="#other">Other link</a>
...
more unrelated tags
...
<div id="other">...</div>
<div id="abc">...</div>

我想知道是否可以用纯CSS而不使用Javascript,为链接设置样式,其 href 是#abc,但只有当元素的 id 也就是 "abc "是由URL锁定的。

css css-selectors
1个回答
0
投票

据我所知,CSS不可能知道当前使用的是什么URL。

唯一可能的(黑客)方法是将元素放在section下面,然后滥用 :hover~ 选择器。但是,说实话,JavaScript的发明是有原因的。

但这也不符合你现在的问题。

#goodbye:hover ~ nav a[href*="#goodbye"], #hello:hover ~ nav a[href*="#hello"] {
  font-weight: bold;
  color: cyan;
}

/* other styling */
html {
  scroll-behavior: smooth;
  margin: 0;
  padding: 0;
}

section {
  height: 105vh;
  padding: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

#hello {
  background: lightgrey;
}

#goodbye {
  background: salmon;
}

nav {
  height: 5vh;
  padding: 10px;
  position: fixed;
  background: white;
  width: 100%;
  top: 0;
}
<section id="hello">
  <h1>Hello</h1>
  <a href="#hello">hello</a>
  <a href="#goodbye">Goodbye</a>
</section>

<section id="goodbye">
  <h1>Goodbye</h1>
  <a href="#hello">hello</a>
  <a href="#goodbye">Goodbye</a>
</section>

<nav>
  <a type="checkbox" href="#hello">hello</a>
  <a href="#goodbye">Goodbye</a>
</nav>
© www.soinside.com 2019 - 2024. All rights reserved.