是否有用于在html中选择元素futherup的css选择器?

1 html css css-selectors

在下面的HTML中,我希望h2在悬停图像时将悬停效果应用于标题img.有没有一个css选择器来做到这一点,或另一种方式?

HTML

  <article>
      <h2><a href="#">Title</a></h2>
      <a href="#"><img src="#" /></a>
  </article>
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 5

更新:主题说明符似乎已从2014年5月6日的选择器级别4规范的编辑草案中删除.这使得无法使用CSS实现此目的.


选择器等级4引入了主题说明符,它允许:

!h2 + a img:hover { }
Run Code Online (Sandbox Code Playgroud)

选择<h2>.

浏览器支持是AFAIK,目前不存在.

你可以在JavaScript中模拟它(以下是未经测试的,但应该给你一个想法).

var img = document.querySelector('h2 + a img');
img.addEventListener('mouseover', function (e) {
    this.parentNode.previousElementSibling.className += " hovered";
});
img.addEventListener('mouseout', function (e) {
    this.parentNode.previousElementSibling.className = this.parentNode.previousElementSibling.className.replace(/\shovered/g, "");
});
Run Code Online (Sandbox Code Playgroud)