最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make input field background image disappear after text is inputted - Stack Overflow

programmeradmin2浏览0评论

I'd like to make the background image for my input field disappear once the user has typed any amount of text in it. Is there a simple way to do that in javascript? I can get it so the bg disappears while the field is focused, but then it returns once they move on to the next field.

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;
}

I'd like to make the background image for my input field disappear once the user has typed any amount of text in it. Is there a simple way to do that in javascript? I can get it so the bg disappears while the field is focused, but then it returns once they move on to the next field.

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;
}
Share Improve this question edited Apr 28, 2010 at 20:26 Crozin 44.4k13 gold badges91 silver badges136 bronze badges asked Apr 28, 2010 at 20:22 aslumaslum 12.3k16 gold badges53 silver badges73 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

with jquery, you could do something like

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

Or for maximum browser patibility (ahem, IE):

$("input.phone-field").change(function() { $.trim($(this).val()) != "" ? $(this).toggleClass("bg", false) : $(this).toggleClass("bg"); });

And the markup:

<input type="text" class="phone-field bg" />

Just add the background image CSS code to the ".phone-field.bg" selector.

This would remove the background as soon as some text is entered (and bring it back if no text is entered).

$("#inputId").focus(function() {
   if ($(this).value != "") {
     $(this).css("background-image", "none");
   }
}).blur(function() {
   if ($(this).value == "") {
      $(this).css("background-image", "url(/images/phonebg.png)");
   }
});
$('#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);
    }
});
发布评论

评论列表(0)

  1. 暂无评论