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

<!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>

  

posted @ 2020-04-10 16:37  房星凡羽  阅读(2445)  评论(0编辑  收藏  举报