【问题标题】:Change width if text in input is not empty如果输入中的文本不为空,则更改宽度
【发布时间】:2017-05-20 09:19:56
【问题描述】:

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

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

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

谁能告诉我我做错了什么或建议任何替代方法?

【问题讨论】:

  • 显示html。您使用的父容器可能会影响 100% 宽度。
  • 其次,100% 是错字吗?它应该是一个字符串“100%”

标签: javascript jquery input width


【解决方案1】:

您知道“更改”事件会在元素失去焦点后触发,对吧?如果您想立即更改,请使用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>

【讨论】:

    【解决方案2】:

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

    喜欢:

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

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

    【讨论】:

      【解决方案3】:

      因为 100% 不是数字。这是字符串;

      $('#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">

      【讨论】:

        【解决方案4】:

        是的,您有一个错字,请将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%;" />

        【讨论】:

        • keypress 并非在所有情况下都有效。 input 是最好的选择。
        猜你喜欢
        • 2014-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-11
        • 2021-03-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多