h5实现移动端聊天输入框自动增高

200 阅读1分钟

做法:
最外层div高度为auto,由里面的div决定最外层高度,然后textara高度为100%;
监听textarea的input事件,获取textarea的值,同时把获取的值使用innerText,赋值给里层div;
这样里层div撑起外层div的高度,同时因为textarea高度为100%,所以textarea的高度就跟外层div高度一样,这样就实现了输入框的自动高度

<style>
    .inputBox {
        position: relative;
        width: 200px;
        height: auto;
        font-size: 16px;
        overflow: hidden;
        border: 1px solid #ccc;
    }

    .hideText {
        width: 100%;
        height: auto;
        min-height: 24px;
    }

    textarea {
        position: absolute;
        top: 0;
        left: 0;
        width: 100% !important;
        height: 100%;
        font-size: 16px;
        background-color: #fff;
        padding: 0;
        box-sizing: content-box;
        overflow: hidden;
        border: none;
        outline: none;
        resize: none;
    }
</style>
   <div class="inputBox">
        <div class="hideText">
        </div>
        <textarea></textarea>
    </div>
    let textarea = document.querySelector('textarea');
    textarea.addEventListener('input', function (e) {
        console.log(e.target.value);
        document.querySelector('.hideText').innerText = e.target.value;
    }, true)

直接复制预览