Make input field background image disappear after text is inputted

前端 未结 4 544
北荒
北荒 2021-01-24 07:59

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 i

相关标签:
4条回答
  • 2021-01-24 08:01

    with jquery, you could do something like

     $('#phone').focus(function(){
         var text = $(this).val();   
         if(text != ''){
            $(this).css('background-image', 'none');       
         }
     });
    
    0 讨论(0)
  • 2021-01-24 08:02

    Or for maximum browser compatibility (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).

    0 讨论(0)
  • 2021-01-24 08:14
    $('#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 讨论(0)
  • 2021-01-24 08:19
    $("#inputId").focus(function() {
       if ($(this).value != "") {
         $(this).css("background-image", "none");
       }
    }).blur(function() {
       if ($(this).value == "") {
          $(this).css("background-image", "url(/images/phonebg.png)");
       }
    });
    
    0 讨论(0)
提交回复
热议问题