【问题标题】:Remove hover style on parent when hovering on child with CSS [duplicate]使用 CSS 悬停在子级上时删除父级上的悬停样式 [重复]
【发布时间】:2015-05-31 21:13:46
【问题描述】:

我有一个小提琴: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 时,我希望所有&lt;p&gt; 标记都改变颜色,除了#divChild 中的&lt;p&gt;。然后,当我将鼠标移动到#divChild 时,我希望其中的所有&lt;p&gt; 标签都改变颜色,并将#divParent&lt;p&gt; 恢复为原来的颜色。

我无法删除或更改类 .myhover 或使用 javascript。我怎样才能只用 CSS 做到这一点?

编辑:

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

【问题讨论】:

  • 你能改变HTML结构吗?

标签: javascript html css


【解决方案1】:

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

【讨论】:

  • 您的否决票可能来自 sancho,因为他似乎对所有答案都投了反对票,如下面被所有者删除的 6 个答案所示。
猜你喜欢
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
  • 2013-07-29
  • 2022-11-03
  • 2012-10-07
  • 1970-01-01
  • 2015-01-10
相关资源
最近更新 更多