使用CSS将鼠标悬停在子项上时,删除父项上的悬停样式

时间:2015-03-27 13:58:16

标签: javascript html css

我有一个小提琴:http://jsfiddle.net/a80h6pts/1/

<style>
.myhover {
  width: 120px;
}
.myhover:hover p{
    color: #FED242!important;
}
</style>
<div id="divParent" class="myhover">
    <p>Some text</p>
    <p>Text text text</p>
    <div id="divChild" class="myhover">
        <p>Example text</p>
    </div>
</div>

当我的鼠标激活#divParent时,我希望所有<p>标记都改变颜色,但<p>内的#divChild除外。然后,当我将鼠标移动到#divChild时,我希望其中的所有<p>标记都会更改颜色,而<p>的{​​{1}}会恢复为原始颜色。

我无法删除或更改班级#divParent或使用javascript。我怎么能只使用CSS?

编辑:

糟糕的是,有些人认为我必须使用js。我可以使用js(jquery)对html / css的影响很小。

1 个答案:

答案 0 :(得分:0)

使用jQuery,您可以使用:

$('#divParent').mouseover(function () {
    $('#divParent > p').addClass('hover')
}).mouseout(function () {
    $('#divParent > p').removeClass('hover')
})
$('#divChild').mouseover(function (e) {
    e.stopPropagation();
    $('#divChild > p').addClass('hover')
}).mouseout(function (e) {
    $('#divChild > p').removeClass('hover')
})
.myhover {
    width: 120px;
}
.hover {
    color: #FED242;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="divParent" class="myhover">
    <p>Some text</p>
    <p>Text text text</p>
    <div id="divChild" class="myhover">
        <p>Example text</p>
    </div>
</div>

正如其他人已经注意到的那样,由于没有父CSS选择器,所以不能单独使用CSS。