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

Remove hover style on parent when hovering on child with CSS

本文关键字:悬停 对象 删除 样式 CSS 使用 鼠标      更新时间:2023-09-26

我有一把小提琴: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的over时,我希望除了#divChild中的<p>之外,所有<p>标签都更改颜色。然后,当我将鼠标移动到#divChild时,我希望其中的所有<p>标签都更改颜色,并将#divParent<p>恢复为其原始颜色。

我无法删除或更改类.myhover或使用javascript。我怎么能只使用CSS呢?

编辑:

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

使用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。