$ .css()不使用:hover和:active伪类

时间:2014-02-28 09:58:10

标签: jquery css

我想知道为什么使用button:hoverbutton:active$.css()无法正常工作

button {
    background: #781111;
    color: white;
}

<button>test</button>

$('button:hover').css({
    'background':'#fe2000'
});

$('button:active').css({
    'background':'#d50d04'
});

当鼠标悬停并单击时,该按钮仍然以相同的方式显示。还有另一种方法吗?

JSFiddle

4 个答案:

答案 0 :(得分:5)

您可以改用纯css:

button:hover {
    background: #fe2000
}

button:active {
    background: #d50d04
}

我建议您使用CSS而不是javascript来实现可以通过两种方式完成的任何任务。

答案 1 :(得分:3)

这是一个全jQuery方法

var $this = $('button')
    .on('mouseout mouseup', function() {
        // Normal
        $this.css('background', initialColor);
    })
    .mouseover(function() {
        // Hover
        $this.css('background', '#ff0000');
    })
    .mousedown(function() {
        // Active
        $this.css('background', '#00ff00');
    }),
    initialColor = $this.css('background');

JSFiddle

答案 2 :(得分:1)

应用css的最佳方法

button:hover {
    background: #fe2000
}

button:active {
    background: #d50d04
}

答案 3 :(得分:0)

您应该使用事件$.hover$.focus,而不是使用像这样的悬停和有效选择器。

相关问题