Javascript 模糊后从焦点应用的还原样式

Javascript 模糊后从焦点应用的还原样式,javascript,jquery,Javascript,Jquery,当用户关注某个文本字段时,我希望该文本字段中的文本更改颜色(以及其他几个属性)。当用户离开该字段(模糊)时,我希望文本/样式显示为焦点之前的状态。目前,我正在以一种似乎是重复的方式做这件事 $('#name1').focus(function() { $(this).css('color', 'red') }); $('#name1').blur(function() { $(this).css('color', 'black') }); 我该怎么做,比如: $('#n

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

$('#name1').focus(function() {
    $(this).css('color', 'red')
});
$('#name1').blur(function() {
        $(this).css('color', 'black')
});
我该怎么做,比如:

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


定义css样式,说明它应该如何聚焦,并在模糊时将其删除

.input_focus {
   color: red;
}
还有剧本

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

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

定义css样式的聚焦方式,并在模糊时将其删除

.input_focus {
   color: red;
}
还有剧本

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

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

按照Vega的建议,使用
toggleClass()


按照Vega的建议,使用
toggleClass()


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

$('#name1').focus(function() {
    $(this).removeClass("blurred").addClass("focused");
}).blur(function() {
    $(this).removeClass("focused").addClass("blurred");
});
或者,如果您不想这样做,或者不同的输入有不同的值,您可以使用
数据

$('#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"));
});

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

$('#name1').focus(function() {
    $(this).removeClass("blurred").addClass("focused");
}).blur(function() {
    $(this).removeClass("focused").addClass("blurred");
});
或者,如果您不想这样做,或者不同的输入有不同的值,您可以使用
数据

$('#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"));
});

如果在
焦点中应用了十种样式,该怎么办?我正在寻找一种方法来删除以最干燥的方式应用的所有样式。使用addClass()和removeClass()?如果在
焦点中应用了十种样式怎么办?我正在寻找一种方法来删除以最简单的方式应用的所有样式。使用addClass()和removeClass()?请您解释一下这行的作用:
var$this=$(this)。为什么不能直接使用
$(this).数据(…)
?您可以使用
$(this)
,但每次使用
$(this)
都会调用jquery。如果要多次使用它,最好将其保存到变量中并重新使用。这是一个小优化。假设每次调用
getMyElement()
,您可能只会将其保存到一个变量中。这里也有同样的想法。@David542最好缓存jQuery对象,而不是将其引用为
$(this)
。如果
$(this)
只使用了一次,那么缓存它就没有意义了。请您解释一下这一行的作用:
var$this=$(this)。为什么不能直接使用
$(this).数据(…)
?您可以使用
$(this)
,但每次使用
$(this)
都会调用jquery。如果要多次使用它,最好将其保存到变量中并重新使用。这是一个小优化。假设每次调用
getMyElement()
,您可能只会将其保存到一个变量中。这里也有同样的想法。@David542最好缓存jQuery对象,而不是将其引用为
$(this)
。如果
$(此)
仅使用一次,则缓存它没有意义。只需确保
.input\u focus
具有足够的优先级来覆盖最初应用的任何样式。只需确保
.input\u focus
具有足够的优先级来覆盖最初应用的任何样式。