textarea文域高度自适应

textarea高度自适应

<textarea>文本域高度随内容自动变化,不会出现滚动条,能够有多种方法,除了用js动态设置它的高度值之外还有其它更简单的方法。html

能够用div标签模拟textarea,将divcontenteditable属性设置成true,使内容可编辑,达到高度随内容变化的目的。contenteditable兼容性很好。this

<div contenteditable='true'></div>

还有一种方法,利用兄弟节点撑开父级高度,设置textarea高度为100%便可。spa

<style>
    .wrap { position: relative; }
    textarea { position: absolute; top: 0; left: 0; height: 100%; }
</style>

<div class="wrap">
    <pre><span></span><br></pre>
    <textarea name="" id="" ></textarea>
</div>
document.querySelecotr('textarea').oninput = function () {
    document.querySelector('pre span').innerHTML = this.value;
}
相关文章
相关标签/搜索