html - CSS 将鼠标悬停在一个段落上,更改上一个段落的背景

标签 html css

为了练习和训练 CSS,我正在尝试做类似的事情: enter image description here

换句话说,我正在尝试这样的事情:当我将鼠标悬停在第三段上时,第二段需要像图片一样获得颜色。

我正在尝试使用伪类 :hover:before(或 :after)和 content 属性设置为 "",设置 background#E7A51Bopacity0.3 但它不起作用。

HTML 需要像这样:

<body>
    <div class="app">
        <p> First paragraph </p>
        <div class="active">
            <p> Second paragraph </p>
        </div>
        <br>
        <div>
            <p> Third paragraph </p>
        </div>
    </div>
</body> 

编辑:感谢大家的评论。阅读您的评论,我想问是否有可能采用更通用的方法,例如:
如果我将鼠标悬停在 class="foo1" 背景元素上 class="foo2" 元素会发生变化吗?

最佳答案

当前 CSS (Selectors Level 3)

不幸的是,对于当前的 CSS 标准,您所尝试的是不可能的。但是,目前有什么可能呢?

给定以下标记:

<div class="app">
    <p> First paragraph </p>
    <p> Second paragraph </p>
    <p> Third paragraph </p>
</div>

您可以定位同一级别(同一父级)上的元素并跟随您与之交互的初始元素(例如 :hover)。 → Demo

/* targeting the direct descending sibling of the 3rd paragraph*/
p:nth-of-type(3):hover + p{
    color:red;
}
/* targets the 4th paragraph when hovering the second */
p:nth-of-type(2):hover ~ p:nth-of-type(4){
    color:blue;
}
/* targets all paragraphs being siblings of the first paragraph */
p:first-of-type:hover ~ p{
    color:green;
}

future (Selectors Level 4)

Selectors Level 4 将(很可能)带来两个令人兴奋的新功能,它们可以实现您实际尝试做的事情:

1) - 我称之为 - subject indicator - 它让您确定要定位复合选择器的哪个元素。

!OL > LI:only-child

将以只有一个列表元素的所有有序列表为目标(看起来很简单,但在当前的 css 下是不可能的)。

2) reference combinator :

label:hover /for/ input

将以输入元素为目标,当通过它的 for 属性引用它的标签悬停时。

目前这还没有被任何浏览器支持,但是你看,我们可以为在不久的将来等待我们的 css 感到兴奋;)

关于html - CSS 将鼠标悬停在一个段落上,更改上一个段落的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17393905/

相关文章:

JavaScript 已禁用

html - clearfix 父级上的额外空间

html - css 悬停图像和显示图标不显示

html - 悬停在其他元素上时停止元素的 move

javascript - 如何验证电子邮件和最小长度验证

javascript - 将触摸事件分配给 Canvas 中的元素 - iPad

html - 我如何响应地处理包装图像和文本的 div?

javascript - scrollTop 和 html 溢出 : hidden

css - 如何增加 PNotify 字体大小?

html - CSS 表格 cellpadding 和 cellspacing?