使用CSS更改悬停元素的颜色 [英] Change color of sibling elements on hover using CSS

查看:176
本文介绍了使用CSS更改悬停元素的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的HTML

 < h1> Heading< / h1> 
< a class =buttonhref =#>< / a>

我想要做的是,当我悬停< a> 标签,我想改变纯粹使用CSS的< h1> 标签的颜色。如何实现?



PS
----- *编辑* ----------



如果我在其中包含一个带有id的div,该怎么办?

 < div id =banner> 
< h1>标题< / h1>
< a class =buttonhref =#>< / a>
< / div>

方案

没有 CSS选择器可以执行此操作( in CSS3,even )。 CSS中的元素从来不知道它们的父级,所以你不能做 a:parent h1 (例如)。它们也不是意识到自己的兄弟姐妹(在大多数情况下),所以你不能做 #container的:悬停{/ *做兄弟H1 *的东西/} 。的基本上,CSS属性不能修改任何东西,但内容和他们的孩子(他们不能访问的父母或兄弟姐妹)。



您可以包含 h1 a ,但这会使您的 h1 hoverable为好。



您将只能够做到这一点使用JavaScript(的 jsFiddle proof-of-concept )。这看起来像这样:

  $(a.button)。hover(function(){
$ (本).siblings(H1)addClass(your_color_class);
},函数(){
$(本).siblings(H1)removeClass移除(your_color_class) ;
});


Below is my HTML

<h1>Heading</h1>
<a class="button" href="#"></a>

What I want to do is, when I hover the <a> tag, I want to change the colour of <h1> tag purely using CSS. How can I achieve this?

PS ----- * Edited * ----------

What if I wrap a div around it with an id in it?

<div id="banner">
    <h1>Heading</h1>
    <a class="button" href="#"></a>
</div>

Will this help?

解决方案

There is no CSS selector that can do this (in CSS3, even). Elements, in CSS, are never aware of their parent, so you cannot do a:parent h1 (for example). Nor are they aware of their siblings (in most cases), so you cannot do #container a:hover { /* do something with sibling h1 */ }. Basically, CSS properties cannot modify anything but elements and their children (they cannot access parents or siblings).

You could contain the h1 within the a, but this would make your h1 hoverable as well.

You will only be able to achieve this using JavaScript (jsFiddle proof-of-concept). This would look something like:

$("a.button").hover(function() {
    $(this).siblings("h1").addClass("your_color_class");
}, function() {
    $(this).siblings("h1").removeClass("your_color_class");
});

这篇关于使用CSS更改悬停元素的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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