html文本域textarea高度自增、自动换行

时间:2023-03-09 23:07:46
html文本域textarea高度自增、自动换行

文本域自动换行、高度自增,采用以下方式:

html:

<textarea rows="1" class="answerTextArea" maxlength="60"></textarea>

css:

.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实现功能:

//监听文本域输入,高度自动变化
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("");

效果如下:

html文本域textarea高度自增、自动换行

html文本域textarea高度自增、自动换行