仅使用 jQuery 库,您无法为背景颜色设置动画。但是您可以在其上使用 jQuery UI 为其设置动画。
所以这很好用
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function(){
$('input.login_reg_input').focus(function () {
$(this).animate({
'backgroundColor': '#768'
}, 250, 'linear', function() { });
});
});
</script>
</head>
<body>
<input class="login_reg_input">click me</input>
</body>
</html>
几年后,这里有更好的选择:
使用 CSS3
jsFiddle
input.login_reg_input {
-ms-transition: background-color 1s;
-o-transition: background-color 1s;
-moz-transition: background-color 1s;
-webkit-transition: background-color 1s;
transition: background-color 1s;
}
input.login_reg_input:focus {
background-color: #789;
}
仅使用 jQuery(不使用 jQuery UI)
jsFiddle
$('input.login_reg_input').focus(function () {
var $elem = $(this),
cnt = 0,
from = { // animate from white (reg, green, blue) 255
r: 255,
g: 255,
b: 255
},
to = { // to #778899 (119, 102, 136)
r: 119,
g: 102,
b: 136
};
// interpolate "from" color to the "to" color
$(from).animate(to, {
duration: 1000,
step: function(now) {
// step is invoked for each r, g and b.
if (++cnt % 3 === 0) { // I want to process only when the whole triple is interpolated
$elem.css('background-color',
'rgb('
+ Math.round(this.r) + ','
+ Math.round(this.g) + ','
+ Math.round(this.b) + ')');
}
// confused? Just uncomment line below and you will get the hang of it
// console.log(now, this);
}
});
});