CSS - 悬停链接时更改另一个元素的样式?

2022-01-22 00:00:00 hover opacity html css

当链接悬停时如何更改另一个元素的样式 - 没有 jQuery/JavaScript?

How can I change the style of another element when a link is hovered - without jQuery/ JavaScript?

ul>li>a:hover main {
  opacity: 0.1;
}

main p {
  font-size: 200px;
}

<header>
  <ul>
    <li><a href="#">Hover me</a></li>
  </ul>
</header>

<main>
  <p>Hello World!</p>
</main>

我想在链接悬停时更改main中文本的opacity.

I want to change the opacity of the text in main when the link is hovered.

有可能吗?

编辑

我尝试了一个兄弟姐妹:

I tried with a sibling:

a:hover ul {
  opacity: 0.5;
}

<header>
  <ul>
    <li><a href="#">Hover me</a><span></span>
      <ul>
        <li>Child 1</li>
        <li>Child 2</li>
        <li>Child 3</li>
      </ul>
    </li>
  </ul>
</header>

但是还是不行……

推荐答案

不能使用 +~ 兄弟选择器,因为 <a><main> 元素不是同级元素.因此,您可以使用 JavaScript.例如,可以在 fadeTo() 内使用 hover() 方法:

It is not possible to use + or ~ sibling selectors, becouse <a> and <main> elements are not siblings. Thus you could use JavaScript. For example it is possible using by fadeTo() within hover() method:

$("a[data-opacity-target]").hover(function() {
  var selector = $(this).data("opacity-target");
  $(selector).fadeTo(500, 0.1);
}, function() {
  var selector = $(this).data("opacity-target");
  $(selector).fadeTo(500, 1);
});

main p {
  font-size: 200px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
  <ul>
    <li><a href="#" data-opacity-target="main">Hover me</a></li>
  </ul>
</header>
<main>
  <p>Hello World!</p>
</main>

在您的 EDIT 部分中,您应该使用 a:hover~ul 选择器而不是 a:hover ul.

In your EDIT section you should use a:hover~ul selector instead of a:hover ul.

相关文章