CSS特殊悬停

时间:2014-11-20 21:04:10

标签: html css css3 hover

http://jsfiddle.net/98bzqoq1/

有没有办法对Class =“c”进行悬停效果,因此它会影响Class =“d”的背景颜色

//到目前为止我的代码

<div>
    <ul>
        <li class="c">Caroline</li>
        <li class="c">Emilia</li>
    </ul>
</div>
<div class="d">This text should be in a green box...</div>

//不起作用

.c:hover ~ .d {
    background: lightgreen;
}

2 个答案:

答案 0 :(得分:2)

根据您提供的代码,您可以执行此操作,因为您的div中唯一的内容是您的列表

div:hover ~ .d {
    background: lightgreen;
}

http://jsfiddle.net/98bzqoq1/1/

但是,如果您的代码更复杂,那么仅使用CSS

是不可能的

答案 1 :(得分:0)

只有当其他元素是具有伪类的元素的直接或间接兄弟或子元素(例如:hover或{{1>时,才能使用伪类作为修改其他元素的操作。 }})。这是因为CSS child/sibling selectors是相当严格的。

您可以使用:focus选择器选择直接子项,使用>选择器选择相邻的兄弟,并使用+选择器选择一般后续兄弟。例如,如果您有以下HTML:

~

您可以使用CSS将相邻的兄弟节点设置为<div> <div class="c">Hover Me!</div> <div> This is a direct adjacent sibling to the element with class "c". </div> </div> <div class="d"> This is an arbitrary element. It is neither a child nor sibling of an element with class "c". It cannot be selected as a result of a pseudo-class action on the textfield using CSS, but can be selected using client-side scripting such as JavaScript or jQuery. </div> ,但由于div class="c"被悬停(因为它既不是孩子也不是兄弟姐妹,因此无法对任意段落进行样式设置)它是父母的兄弟姐妹)而不使用客户端脚本(JavaScript,jQuery等)。

使用jQuery div class="c"函数,您可以实现最终目标。例如,以下代码将设置任意段落的样式,并且可以更改为选择页面上的任何元素(只需将元素的CSS选择器作为参数传递给.hover()函数):

$()

Here is an example演示了CSS和jQuery方法。