2

这里是小提琴。我正在尝试通过使用<div>和应用颜色来制作自己的复选框$().css()。当您单击 时div,我试图$().toggleClass()在单击功能中使用将背景颜色更改为#96f226

jQuery:

$('div').mouseenter(function(){
    $(this).css('background','#656565');
});
$('div').mouseleave(function(){
    $(this).css('background','#4a4a4a');
});
$('div').click(function(){
    $(this).toggleClass('active');
});

HTML:

<div></div>

CSS:

div {
    width: 15px;
    height: 15px;
    background: #4a4a4a;
    cursor: pointer;
}
.active {
    background: #96f226
}
4

5 回答 5

5

通过.css调用“背景”属性,您可以更改元素的相应内联样式,指定为其属性。换句话说,你的mouseenter处理程序变成<div><div style="background: ##656565">. mouseleave以类似的方式工作,只是style属性的值不同。

问题在于以这种方式设置的样式规则 - 在属性内 -比作为 CSS 规则集中给出的类匹配规则(或选择器的任何组合)的结果应用的规则style具有最高的特异性。

这就是为什么在将类添加到元素时看不到任何更改的原因active(并且很容易检查确实添加了类;这只是它的规则没有考虑)。

mouseenter如果您完全删除所有对内联样式的摆弄,并使用另一个类 -设置和删除处理程序,那么这个问题很容易解决mouseleave

但实际上,您甚至不需要这样:您尝试处理的事件已经由浏览器以非常好的方式处理。它很容易利用:只需为:hover伪类设置样式规则,如下所示:

div:hover {
    background: #656565
}
div.active, div.active:hover {
    background: #96f226
}

这是一个可以玩的小提琴。

于 2013-09-04T00:33:16.073 回答
1

这是因为 a 的优先级class低于style属性。

于 2013-09-04T00:32:02.333 回答
0

当您直接在元素上设置 CSS 属性时,这将优先于您切换的类。要使其工作,您必须添加另一个类。

.enter {
   background: #656565;
}

然后你的 JS 会是这样的:

$('div').mouseenter(function(){
   $(this).addClass("enter");
});
$('div').mouseleave(function(){
   $(this).removeClass("enter");
});
$('div').click(function(){
   $(this).toggleClass('active');
});

看到这个小提琴http://jsfiddle.net/w8yuZ/5/

于 2013-09-04T00:34:51.233 回答
0

试试这个:

$(function(){

    $('div').mouseenter(function(){
        $(this).css('background','#656565');
    });

    $('div').mouseleave(function(){
        $(this).css('background','#4a4a4a');
    });

    $('div').click(function(){
        $(this).toggleClass('active');
    });

});
于 2013-09-04T00:35:00.767 回答
-3

这将帮助您:

.active {
    background: #96f226 !important;
}
于 2013-09-04T00:33:20.587 回答