【问题标题】:How to highlight all matched elements when hover each of them?悬停每个匹配的元素时如何突出显示所有匹配的元素?
【发布时间】:2019-11-03 12:51:08
【问题描述】:

我被Highlight all elements with same class when one of them is moused over引用

我想知道的方式是——用 CSS 可以吗?

我正在尝试使用 sibling: ~,但它无法突出显示之前的兄弟元素。

.test {
  color: blue;
}
.test:hover, .test:hover ~ .test {
  color: red;
  cursor: pointer;
}
<div>
  <span class="prev">Test Highlight by mouse over the `blue` texts: </span>
  <span class="test">This </span>
  <span class="test">Is </span>
  <span class="test">The </span>
  <span class="test">Highlight</span>
</div>

【问题讨论】:

  • 这不是你发现的——因为 CSS 选择器缺乏向后遍历级联的能力——这可以通过 CSS 实现;但感谢您提示我更新我之前完全忘记的答案。
  • 谢谢@DavidThomas,所以唯一的解决办法就是使用javascript,对吧?
  • 不幸的是,是的(CSS selectors level 4 有一个提议的关系伪类 :has()可能允许这样做,但它似乎不太可能在选择器级别 4 的早期阶段。

标签: html css highlight


【解决方案1】:

据我所知,这是不可能的,因为 CSS 目前无法选择任何前面的元素,尽管您可以通过以下方式实现这种行为:

.test {
  color: blue;
}
.x:hover .test {
  color: red;
  cursor: pointer;
}
<span class="prev">Test Highlight by mouse over the `blue` texts: </span>
<span class="x">
  <span class="test">This </span>
  <span class="test">Is </span>
  <span class="test">The </span>
  <span class="test">Highlight</span>
</span>

您可以阅读有关 CSS 无法选择先前元素的更多信息here

【讨论】:

  • 如果我可以将spans 包装到一个父元素中,那么我不需要这个问题。答案比你的简单得多 - x:hover { color: red; }
猜你喜欢
  • 2017-09-28
  • 2015-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
相关资源
最近更新 更多