欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【功能】动态改变input输入框宽度

程序员文章站 2022-06-07 15:38:15
...
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <link rel="stylesheet" type="text/css" href="https://www.layuicdn.com/layui/css/layui.css" />
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/layui.min.js"></script>
  <script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
</head>

<body>
   <input type="text" name="1" placeholder="请输入" value="你好" autocomplete="off" class="layui-input"
    lay-verify="required">
   <input type="text" name="2" placeholder="请输入" value="天王盖地虎" autocomplete="off" class="layui-input"
    lay-verify="required">
   <input type="text" name="3" placeholder="请输入" value="我就是这条该最亮的崽" autocomplete="off" class="layui-input"
    lay-verify="required" size="10">
</body>

<!-- layui -->
<script type="text/javascript">
  layui.use(['transfer', 'laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element'], function () {
    var laydate = layui.laydate //日期
      , laypage = layui.laypage //分页
      , layer = layui.layer //弹层
      , table = layui.table //表格
      , carousel = layui.carousel //轮播
      , upload = layui.upload //上传
      , element = layui.element //元素操作 等等...
      , transfer = layui.transfer;

    // 初始化
    $('input').css({
      'width': function () {
        let em = $(this).css('font-size').split('px', 2)[0]
        return ($(this).val().length + 2.5) * em + 'px'
      }
    })
    // 动态监听
    $('input').on('keyup', function () {
      $(this).css({
        'width': function () {
          let em = $(this).css('font-size').split('px', 2)[0]
          return ($(this).val().length + 2.5) * em + 'px'
        }
      })
    })

  });
</script>


</html>