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

input文本框自适应文本内容宽度
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>input文本框自适应文本内容宽度</title>
</head>
<body>

    <input type="text" id="t1" value="哈哈哈哈哈哈哈哈哈哈哈哈哈或或" />

    <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
        $(function () {
            var text = $("#t1");
            textWidth(text);
        });
        function textWidth($this) {
            var inputVal = $this.val();
            var fontSize = $this.css('font-size');
            var span = document.createElement("span");
            document.body.appendChild(span);
            var $span = $(span);
            $span.text(inputVal).css('font-size', fontSize).hide();
            var width = $span.width();
            $this.css('width', width);
        };
    </script>
</body>
</html>

参考: https://blog.csdn.net/weixin_43804382/article/details/84542732

原文地址:https://www.cnblogs.com/kikyoqiang/p/11398523.html