如果输入中的文本不为空,则更改宽度

Change width if text in input is not empty

如果其中有一些文本,我想将输入字段的宽度设置为 100%。 我尝试了以下 jquery 命令但没有成功。

$("#field").change(function(){
      if($(this).val() != '')
      {
         $(this).css("width",100%);
      }
  });

$('#field').on('change', function() { 
     if($(this).val()!='')
     {
             $(this).css("width",100%);
     }
    });

任何人都可以告诉我我做错了什么或建议任何替代方法吗?

您需要设置一个字符串作为宽度属性的值

喜欢:

$(this).css("width","100%");

否则 js 会将 % 解释为取模运算符而不是单位

你知道 "change" 事件在元素失去焦点后触发,对吧?如果您希望立即更改,请使用 input 事件。

此外,100% 需要用引号引起来,因为这是您希望使用的实际值。

// the change event triggers after the focus is lost on the element
$('#field').on('change', function() { 
     if($(this).val()!=='')     {
             $(this).css("width","100%");
     }
});

// The input event fires as the value changes
$('#field2').on('input', function() { 
     if($(this).val()!=='')     {
             $(this).css("width","100%");
     }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
<input id="field" placeholder="type and then hit TAB">
</div>

<div>
<input id="field2" placeholder="just type">
</div>

因为 100% 不是 number.this 是字符串;

$('#field').on('input', function() {
     if($(this).val() != '')
     {
             $(this).css("width","100%");
     }else{
       $(this).css("width","20%");
     }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field">

是的,你打错了,把100%改成"100%"。如果您想立即更改,请使用 on keypress 或更好的 on input:

$('#field').on('input', function() {
  if ($(this).val() != '') {
    $(this).css("width", "100%");
  }else{
    $(this).css("width", "50%");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field" style="width:50%;" />