【问题标题】:Make input field background image disappear after text is inputted输入文本后使输入字段背景图像消失
【发布时间】:2010-04-28 20:22:09
【问题描述】:

一旦用户在其中输入了任意数量的文本,我想让我的输入字段的背景图像消失。有没有一种简单的方法可以在 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;
}

【问题讨论】:

    标签: javascript html css forms


    【解决方案1】:

    使用 jquery,你可以做类似的事情

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

    【讨论】:

      【解决方案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”选择器即可。

      这将在输入一些文本后立即删除背景(如果没有输入文本,则将其恢复)。

      【讨论】:

      • 那么我应该把java放在哪里? 困惑 我对 javascript 的了解并没有我想象的那么多。
      【解决方案3】:
      $("#inputId").focus(function() {
         if ($(this).value != "") {
           $(this).css("background-image", "none");
         }
      }).blur(function() {
         if ($(this).value == "") {
            $(this).css("background-image", "url(/images/phonebg.png)");
         }
      });
      

      【讨论】:

      • 修正了简单的错字...但仔细看,您的意思也是$(this).val()this.value,但没有$(this).value。也肯定这不会在您键入时删除背景,直到您模糊?总是在焦点上删除背景怎么样,但只有在模糊时为空时才将背景放回去。
      【解决方案4】:
      $('#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);
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2013-12-27
        • 1970-01-01
        • 2018-03-24
        • 1970-01-01
        • 1970-01-01
        • 2013-01-27
        • 2011-08-02
        • 2014-08-09
        • 1970-01-01
        相关资源
        最近更新 更多