js实现input框随输入自适应宽度

时间:2024-03-11 10:58:55
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    a {
        font-size: 14px;
        font-family: simsun;
    }
</style>
<body>
    <input type="text" style="font-size: 14px; width: 2px; padding: 0 10px; font-family: simsun;"> 
</body>
</html>
<script>
    function textWidth(text){
        var sensor = document.createElement(\'a\');
        sensor.innerHTML = text;
        var body = document.getElementsByTagName(\'body\')[0];
        body.appendChild(sensor);
        var width = sensor.offsetWidth;
        body.removeChild(sensor);
        return width;
    };
    var inputdom = document.getElementsByTagName(\'input\')[0];
    inputdom.addEventListener(\'input\', function() {
        var width = textWidth(this.value);
        this.style.width = width +\'px\'
    })
</script>