恢复模糊后从焦点应用的样式

时间:2012-04-23 19:11:37

标签: javascript jquery

当用户关注文本字段时,我希望该文本字段中的文本更改颜色(在其他几个属性中)。当用户离开该字段(模糊)时,我希望文本/样式显示在焦点之前。目前我正在以一种似乎是重复的方式来做这件事。

$('#name1').focus(function() {
    $(this).css('color', 'red')
});
$('#name1').blur(function() {
        $(this).css('color', 'black')
});

我怎么做这样的事情:

$('#name1').blur(function() {
        $(this).beforeFocus();
});

4 个答案:

答案 0 :(得分:4)

定义一个关于它应该如何聚焦的css样式并将其移除onblur。

.input_focus {
   color: red;
}

脚本,

$('#name1').focus(function() {
    $(this).addClass('input_focus')
}).blur(function() {
    $(this).removeClass('input_focus')
});

这样,您可以在聚焦时添加任意数量的样式。

答案 1 :(得分:1)

$('#name1').focus(function() {
    $(this).addClass('focus');
}).blur(function() {
    $(this).removeClass('focus');
});

答案 2 :(得分:1)

理想情况下,我会使用两个不同的css类,并为这些类定义所有适当的属性。那就是这样的:

$('#name1').focus(function() {
    $(this).removeClass("blurred").addClass("focused");
}).blur(function() {
    $(this).removeClass("focused").addClass("blurred");
});

或者,如果您不想这样做或者不同输入的值不同,您可以使用data

$('#name1').focus(function() {
    var $this = $(this);

    $this.data("oldColor", $this.css("color"))
         .css("color", "blue");

}).blur(function() {
    var $this = $(this);

    $this.css("color", $this.data("oldColor"));
});

答案 3 :(得分:0)

使用toggleClass()执行Vega的建议:

$("#name1").focus(function() {
    $(this).toggleClass("inpFocus");
}).blur(function() {
    $(this).toggleClass("inpFocus");
});