js实现textarea自适应高度
html结构:
<div class="container" id="container"> <div class="text-wrapper"> <pre></pre> <textarea placeholder="请输入内容"></textarea> </div> </div>
原理:使用 pre(可以保留空格和换行)元素保存 textarea 的内容,使得父元素 div 的高度撑高,再设置 textarea 的高度为 100%即可
css样式:
*, *:before, *:after { box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; } body { font-size: 14px; font-family: '微软雅黑',"Helvetica Neue", Helvetica, Arial, sans-serif; color: #333; background-color: #fff; line-height: 1.6; } body, div, pre, textarea { margin: 0; padding: 0; } .container { width: 800px; margin: 20px auto; } .text-wrapper { position: relative; margin-bottom: 20px; } .text-wrapper pre { display: block; visibility: hidden; width: 100%; min-height: 40px; padding: 8px 10px; font-size: 14px; line-height: 1.6; border: 1px solid #aed0ea; white-space: pre-wrap; word-break: break-all; word-wrap: break-word; } .text-wrapper textarea { position: absolute; top: 0; left: 0; display: inline-block; width: 100%; height: 100%; box-sizing: border-box; padding: 8px 10px; font-size: 14px; line-height: 1.6; vertical-align: middle; background-color: #fff; border: 1px solid #aed0ea; border-radius: 4px; overflow: hidden; white-space: pre-wrap; word-break: break-all; word-wrap: break-word; resize: none; transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s; -moz-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; } .text-wrapper textarea:focus { border-color: #66afe9; outline: 0; box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6); -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6); -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6); }
js代码:
var laoq = (function(){ var addHandler = function(ele,type,fn){ if(ele.addEventListener){ ele.addEventListener(type,fn,false); }else if(ele.attachEvent){ ele.attachEvent('on' + type,fn); }else{ ele['on' + type] = fn; } }; var setTextareaAutoHeight = function(){ addHandler(document.getElementById('container'),'input',function(){ var event = event || window.event, target = event.target || event.srcElement; if(target.type.toLowerCase() !== 'textarea') return; var preele = target.previousElementSibling; preele && preele.tagName.toLowerCase() === 'pre' && target.parentElement.classList.contains('text-wrapper') && (preele.innerText = target.value); }); }; return{ setTextareaAutoHeight:setTextareaAutoHeight }; })();
调用方式:
window.onload = function(){ laoq.setTextareaAutoHeight(); };