CSS-悬停链接时更改另一个元素的样式吗? [英] CSS - change the style of another element when a link is hovered?

查看:47
本文介绍了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>

但仍然无法正常工作...

But still does not work...

推荐答案

由于< a> ;,因此无法使用 + 兄弟选择器; < main> 元素不是兄弟姐妹.因此,您可以使用JavaScript.例如,可以通过 fadeTo() 使用="https://api.jquery.com/hover/" rel ="nofollow noreferrer"> 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.

这篇关于CSS-悬停链接时更改另一个元素的样式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆