link:visited 不适用于兄弟组合器

link:visited doesn't work with sibling combinator

我需要在访问 link 时更改相邻元素的样式:

a:visited + div { color: #000 }

这不起作用。我该怎么做才能获得我需要的样式?

我在 Specs 中没有找到任何明确禁止兄弟组合器使用此伪 class 的内容,但是:

:visited伪class是一个特例,因为它可能被滥用来侵犯用户隐私。这就是允许浏览器以不同方式对待 :visited 的原因。据我所知,浏览器只是对已访问链接的样式撒谎,同时仍然应用这些样式——从技术上讲,它们将被允许根本不应用 :visited 样式。我假设,大多数供应商刚刚决定,不将样式应用于兄弟组合器(因为这只是我的猜测,如果有人对此有具体的来源,请确认。).

请参阅 spec

中的注释

Note: It is possible for style sheet authors to abuse the :link and :visited pseudo-classes to determine which sites a user has visited without the user's consent.

UAs may therefore treat all links as unvisited links, or implement other measures to preserve the user's privacy while rendering visited and unvisited links differently.

console.log(`Browser is lying about  the color of the i element - should be olive, but is ${window.getComputedStyle(document.querySelector("a i")).color} (red) instead.`);
a{
  color:red;
  display:block;
  text-decoration:none;
  font-size:20px;
}
a:visited{
  color:#bada55;
}
a:visited ~ div{
  color:LightGoldenRodYellow !important;
}
a span{
  color:RebeccaPurple;
}
a:visited i{
  color:Olive;
}
a:last-of-type{
  color:hotpink;
}
a:last-of-type + div{
  color:MediumSeaGreen;
}
<a href="#">Is red while not visited! <span>Is always RebeccaPurple!</span> <i>Should be olive once link is visited!</i></a>
<a href="#">Will be #bada55 when visited!</a>
<a href="#">Will be hotpink!</a>
<div>Should be LightGoldenRodYellow, but is MediumSeaGreen!</div>