[英]Css hover on before element
I have a div and a div:before. 我有一个div和一个div:之前。 I want when the mouse goes over (hover) the :before element to change its color.
我希望当鼠标移过(悬停):before元素以更改其颜色时。 Is there a way to do it no matter with css or jQuery?
有没有办法做到这一点,无论使用CSS还是jQuery?
I tried stuff like div:before:hover but nothing happened 我试过像div这样的东西:之前:悬停但没有发生任何事情
Thanks in advance 提前致谢
(doesn't resolve question) With just css: (不解决问题)只用css:
span:before {
color: red;
content: "hi";
}
span:hover:before {
color: blue;
}
html HTML
<span>text</span>
edit: fiddle http://jsfiddle.net/bwkM6/ 编辑:小提琴http://jsfiddle.net/bwkM6/
Work around for given problem without :before 没有:之前解决给定问题
:before
和:after
伪类不能承担其他伪类属性。
You can't combine pseudo-elements quite like that, apparently. 显然,你不能将伪元素组合起来。 However, you can use jQuery to inject your "
:before
" element into the DOM, rather than doing it with CSS. 但是,您可以使用jQuery将“
:before
”元素注入DOM,而不是使用CSS。
$(function() {
$('div.interesting').before('<div class="interesting-before"></div>');
});
Then in your CSS you just reference .interesting-before
and .interesting-before:hover
instead of .interesting:before
and .interesting:before:hover
. 然后在你的CSS中你只需要引用
.interesting-before
和.interesting-before:hover
而不是.interesting:before
和.interesting:before:hover
。
See http://jsfiddle.net/Z97uN/2/ for an example. 有关示例,请参见http://jsfiddle.net/Z97uN/2/ 。
I see several solutions: 我看到几个解决方案:
EASIEST - you assign specific class to the div:before EASIEST - 您为div指定特定的类:之前
//HTML
<div class="specificClass">A</div>
<div>B</div>
<style>
.specificClass:hover {color: red}
</style>
However from your question it seems you cannot do that. 但是从您的问题看来,你似乎无法做到这一点。 Then leverage jQuery:
然后利用jQuery:
Approach #1 方法#1
//JAVASCRIPT
$("div").prev().addClass("specificClass");
//in your CSS
.specificClass:hover {color:red}
Approach #2 方法#2
//JAVASCRIPT
$("div").delegate($("div").prev(),"mouseenter mouseleave",function(){
$(this).toggleClass("specificClass");
}
//in your CSS
.specificClass {color:red}
please note that you must understand that this will work only if there are only 2 divs. 请注意,您必须明白,只有只有2个div才能使用。 If there are more, all of them but the last will receive the ".specificClass."
如果还有更多,那么除了最后一个都会收到“.specificClass”。 Anyway the same would happen if "span:hover:before" worked.
无论如何,如果“span:hover:before”工作,也会发生同样的情况。
If you explain what and why you want to achieve what you describe we would be able to give better solution. 如果您解释为什么以及为什么要实现您所描述的内容,我们将能够提供更好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.