3

我有一个 div 和一个 div:before。我想当鼠标经过(悬停) :before 元素时改变它的颜色。无论使用 css 还是 jQuery,有没有办法做到这一点?

我尝试了 div:before:hover 之类的东西,但什么也没发生

提前致谢

4

5 回答 5

7

解决方案 1

(不解决问题)仅使用 css:

span:before {
    color: red;
    content: "hi";
}
span:hover:before {
    color: blue;
}

html

<span>text</span>

编辑:小提琴http://jsfiddle.net/bwkM6/

解决方案 2

在没有 :before 的情况下解决给定的问题

http://jsfiddle.net/Z97uN/1/

于 2013-02-05T21:31:23.253 回答
2

:before并且:after伪类不能具有其他伪类属性。

于 2013-02-05T21:29:08.430 回答
1

显然,你不能像那样组合伪元素。但是,您可以使用 jQuery 将“ :before”元素注入 DOM,而不是使用 CSS。

$(function() {
    $('div.interesting').before('<div class="interesting-before"></div>');
});

然后在您的 CSS 中,您只需引用.interesting-beforeand.interesting-before:hover而不是.interesting:beforeand .interesting:before:hover

有关示例,请参见http://jsfiddle.net/Z97uN/2/ 。

于 2013-02-05T22:51:32.757 回答
0

我看到了几个解决方案:

最简单 - 您将特定类分配给 div:before

//HTML
<div class="specificClass">A</div>
<div>B</div>
<style>
.specificClass:hover {color: red}
</style>

但是,从您的问题来看,您似乎无法做到这一点。然后利用 jQuery:

方法#1

//JAVASCRIPT
$("div").prev().addClass("specificClass");

//in your CSS 
.specificClass:hover {color:red}

方法#2

//JAVASCRIPT
$("div").delegate($("div").prev(),"mouseenter mouseleave",function(){
    $(this).toggleClass("specificClass");
}

//in your CSS 
.specificClass {color:red}

请注意,您必须了解这仅在只有 2 个 div 时才有效。如果还有更多,除了最后一个之外,所有这些都将收到“.specificClass”。无论如何,如果“span:hover:before”有效,也会发生同样的情况。

如果您解释什么以及为什么要实现您所描述的,我们将能够提供更好的解决方案。

于 2013-02-05T22:05:17.543 回答
0

正确的语法是

div:hover:before
{
//css here
}

jsfiddle

于 2016-07-10T18:00:23.917 回答