你们知道更好的方法来展示这段代码吗?
$(document).ready(function() {
$("input[type='text']").focus(function() {
$(this).css({ "background-color" : "#f1f1f1" });
});
$("input[type='text']").focusout(function() {
$(this).css({ "background-color" : "white" });
});
$("input[type='email']").focus(function() {
$(this).css({ "background-color" : "#f1f1f1" });
});
$("input[type='email']").focusout(function() {
$(this).css({ "background-color" : "white" });
});
$("input[type='password']").focus(function() {
$(this).css({ "background-color" : "#f1f1f1" });
});
$("input[type='password']").focusout(function() {
$(this).css({ "background-color" : "white" });
});
});
我可以将上面的代码缩短为更小的函数吗?
答案 0 :(得分:4)
此处不需要JavaScript,因为这可以仅在CSS中实现:
var subThoroughfare = p.subThoroughfare ?? ""
self.adress.text = "\(p.thoroughfare) \(subThoroughfare)"
self.adress2.text = " \(p.postalCode) \(p.subLocality)"
答案 1 :(得分:2)
$(document).ready(function() {
$("input[type='text'],input[type='email'],input[type='password']").focus(function() {
$(this).css({"background-color" : "#f1f1f1"});
});
$("input[type='text'],input[type='email'],input[type='password']").focusout(function() {
$(this).css({"background-color" : "white"});
});
});
答案 2 :(得分:0)
尝试:
<强> CSS 强>
.grey {
background-color: #f1f1f1;
}
<强>的jQuery 强>
jQuery(function($) {
var $inputs = $('input[type=email], input[type=text], input[type=password]');
$inputs.on('focus', function() {
$(this).addClass('grey');
});
$inputs.on('blur', function() {
$(this).removeClass('grey');
});
});
答案 3 :(得分:0)
$(document).ready(function(
快捷方式是
$(function(
要减少需要指定选择器的次数(并降低拼写错误的风险),您可以将事件作为数组传递:
$(function() {
$("input[type='text'],input[type='email'],input[type='password']")
.on({
focus: function() { $(this).css({"background-color" : "#f1f1f1"},
focusout: function() { $(this).css({"background-color" : "white"}
);
});
或者你可以链接语句(我的偏好):
$(function() {
$("input[type='text'],input[type='email'],input[type='password']")
.on("focus", function() { $(this).css({"background-color" : "#f1f1f1"})
.on("focusout", function() { $(this).css({"background-color" : "white"});
});
建议您将.addClass
/ .removeClass
与css类一起使用,因为它可以让您更轻松地更改样式(例如,如果您想在输入周围添加发光框)。
答案 4 :(得分:0)
要在CSS中回答您的问题,您可以这样做,
input[type='text'], input[type='email'], input[type='password'] {
background-color : white;
}
input[type='text']:focus, input[type='email']:focus, input[type='password']:focus {
background-color : #f1f1f1;
}
注意:强> CSS不会消耗进程,但javascript会消耗进程。尽可能使用CSS总是最好的。
希望这有帮助。