输入文本后,输入字段背景图像消失

时间:2010-04-28 20:22:09

标签: javascript html css forms

我想让输入字段的背景图像在用户输入任意数量的文本后消失。在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;
}

4 个答案:

答案 0 :(得分:2)

使用jquery,你可以做类似

的事情
 $('#phone').focus(function(){
     var text = $(this).val();   
     if(text != ''){
        $(this).css('background-image', 'none');       
     }
 });

答案 1 :(得分:2)

$("#inputId").focus(function() {
   if ($(this).value != "") {
     $(this).css("background-image", "none");
   }
}).blur(function() {
   if ($(this).value == "") {
      $(this).css("background-image", "url(/images/phonebg.png)");
   }
});

答案 2 :(得分:2)

或者最大化浏览器兼容性(嗯,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”选择器。

一旦输入一些文本,这将删除背景(如果没有输入文本,则将其带回)。

答案 3 :(得分:0)

$('#inputId').focus(function(){
    var newValue = $(this).val();
    if ($(this).val() == ""){
        $(this).css("background-image", "none");
    }else{
        $(this).val(newValue);
    }
}).blur(function(){
    var newValue = $(this).val();
    if ($(this).val() == ""){
        $(this).css("background-image", "url(/images/phonebg.png)");
    }else{
        $(this).val(newValue);
    }
});