textarea文域高度自适应

textarea高度自适应

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

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

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

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

<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;
}

猜你喜欢

转载自www.cnblogs.com/homehtml/p/12805968.html