文本域自動換行、高度自增,採用如下方式:css
html:html
<textarea rows="1" class="answerTextArea" maxlength="60"></textarea>
css:spa
.answerTextArea{ width: 100%; height: auto; border:none; outline: none; font-size: 0.6rem; color:#fff; background: none; box-sizing: border-box; padding: 0.4rem 0; border-bottom: 1px solid #fff; }
js實現功能:code
//監聽文本域輸入,高度自動變化 function makeExpandingArea(el) { var timer = null; //因爲ie8有溢出堆棧問題,故調整了這裏 var setStyle = function(el, auto) { if (auto) el.style.height = 'auto'; el.style.height = el.scrollHeight + 'px'; } var delayedResize = function(el) { if (timer) { clearTimeout(timer); timer = null; } timer = setTimeout(function() { setStyle(el) }, 200); } if (el.addEventListener) { el.addEventListener('input', function() { setStyle(el, 1); }, false); setStyle(el) } else if (el.attachEvent) { el.attachEvent('onpropertychange', function() { setStyle(el) }) setStyle(el) } if (window.VBArray && window.addEventListener) { //IE9 el.attachEvent("onkeydown", function() { var key = window.event.keyCode; if (key == 8 || key == 46) delayedResize(el); }); el.attachEvent("oncut", function() { delayedResize(el); }); //處理粘貼 } } //監聽文本換行 function exeTextLine(obj){ if(obj == ""){ var textareaList = document.getElementsByClassName('answerTextArea'); for(var i=0;i<textareaList.length;i++){ makeExpandingArea(textareaList[i]); } }else{ makeExpandingArea(obj); } } exeTextLine("");
效果以下:htm