Is there a css selector for selecting an element futherup in the html?(是否有用于在 html 中选择元素的 css 选择器?)
问题描述
在下面的 HTML 中,我想在图像 img
悬停时对标题 h2
应用悬停效果.是否有一个 css 选择器可以做到这一点,或者其他方式?
In the following HTML, I want to apply a hover effect to the header h2
, upon hover of the image img
. Is there a css selector to do that, or another way?
HTML
<article>
<h2><a href="#">Title</a></h2>
<a href="#"><img src="#" /></a>
</article>
推荐答案
更新:主题说明符似乎已从 Selectors Level 4 规范的Editor's Draft,2014 年 5 月 6 日中删除.这使得使用 CSS 无法实现这一点.
Update: The subject specifier appears to have been removed from the Editor’s Draft, 6 May 2014 of the Selectors Level 4 specification. This leaves no way to achieve this using CSS.
选择器级别 4 引入了 主题说明符,它允许:
Selectors Level 4 introduces the subject specifier which allows:
!h2 + a img:hover { }
选择<h2>
.
浏览器支持,AFAIK,目前不存在.
Browser support is, AFAIK, currently non-existent.
您可以在 JavaScript 中模拟它(以下内容未经测试,但应该会给您一些想法).
You can simulate it in JavaScript (the following is untested, but should give you the idea).
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, "");
});
这篇关于是否有用于在 html 中选择元素的 css 选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!