input文本框自适应文本内容value宽度

本文介绍如何实现input输入框的宽度能够根据输入的文本内容自适应调整,确保文字完整显示,提高用户体验。
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
   <input type="text" style="width: 100px ;font-size: 14px;" value="静静的敲代码" class="input_auto">
   <input type="text" style="width: 100px;font-size: 20px" value="算了,先找对象吧"  class="input_auto">
   <span  class="spanw"></span>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
  
  jQuery(document).ready(function($){
    // 第一次加载设置input宽度
    $('.input_auto').each(function(index, el) {
       textWidth($(this))
    });
    // 改变文本内容时重置宽度
    $('.input_auto').bind('input oninput', function() { 
       textWidth($(this))
    });

     function textWidth($this){ 
      // 获取当前input的value值和字体大小
       var inputVal=$this.val();
       var font=$this.css('font-size');
       //获取容器的宽度
       $(".spanw").text(inputVal).css('font-size',font);; 
       var width = $(".spanw").width();
       // 清空容器
       $(".spanw").text(''); 
       // 设置input宽度
       $this.css('width', width);
    };
   
  });

</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值