输入文本后输入字段背景图像消失
问题描述:
我想让输入字段的背景图像在用户键入任意数量的文本后消失。有没有一种简单的方法来在JavaScript中做到这一点?我能得到它,所以bg在领域集中时消失,但是一旦他们移动到下一个领域,它就会返回。输入文本后输入字段背景图像消失
HTML:Call me at <input name="phone" type="text" class="phone-field" id="phone">
CSS:
.form input {
background-color:transparent;
}
.form input:focus {
background-color:#edc;
background-image:none;
}
input.phone-field {
background-image: (url/images/phonebg.png);
background-repeat: no-repeat;
background-position: left 1px;
}
答
使用jQuery,你可以不喜欢
$('#phone').focus(function(){
var text = $(this).val();
if(text != ''){
$(this).css('background-image', 'none');
}
});
答
$("#inputId").focus(function() {
if ($(this).value != "") {
$(this).css("background-image", "none");
}
}).blur(function() {
if ($(this).value == "") {
$(this).css("background-image", "url(/images/phonebg.png)");
}
});
答
或者最大的浏览器兼容性(啊哈,IE):
$("input.phone-field").change(function() { $.trim($(this).val()) != "" ? $(this).toggleClass("bg", false) : $(this).toggleClass("bg"); });
而且标记:
<input type="text" class="phone-field bg" />
只是背景图片的CSS代码添加到 “.phone-field.bg” 选择。
只要输入一些文字(如果没有输入文字,则将其恢复),这将删除背景。
+0
那么我在哪里把Java? * confused *我并没有像我以前那样真正理解JavaScript。 – aslum 2010-04-29 17:56:38
答
修复了简单的错字...但是看着它,你也意味着$(this).val()或this.value,但是没有$(this).value '。当然,当你输入时,这肯定不会消除背景,直到你模糊了?如何总是删除焦点背景,但只有在模糊时将背景放回。 – bobince 2010-04-28 20:56:58