textarea高度自適應
有時候寫表單的時候,會有一個 備注框textarea。
因為textarea不支持自適應高度,就是定好高度或者是行數之后,超出部分就會顯示滾動條,看起來不美觀。
我們需要美觀實現的效果:默認顯示一行。當輸入的文字超過一行或者輸入Enter時,
輸入框的高度會隨着改變,直到輸入完畢。也就是要實現textarea的高度自適應
=========================================================
方案A:用div來模擬textarea實現的,用CSS控制樣式,不用JS。
而用DIV來模擬時,首先遇到的問題是:div怎么實現輸入功能?
一個普通的block元素上加個contenteditable="true"就實現編輯,出現光標了。
如<div contenteditable="true"></div>
<div class="test-textarea" contenteditable="true" ><br /></div>
.test-textarea {
width: 400px;
min-height: 26px;
line-height: 20px;
_height: 30px;
/* max-height: 150px;*/
margin-left: auto;
margin-right: auto;
padding: 3px;
outline: 0;
border: 1px solid #ccc;
font-size: 12px;
word-wrap: break-word;
overflow-x: hidden;
overflow-y: auto;
-webkit-user-modify: read-write-plaintext-only;
border-radius: 4px;
}
===================================================
方案B:Js實現textarea自適應
.text-adaption {
width: 300px;
height: 34px;
overflow: hidden;
padding: 5px 10px;
resize: none;
line-height: 24px;
font-size: 12px;
color: #666;
border: 1px solid #ccc;
outline: 0 none;
border-radius: 3px;
box-sizing: border-box;
}
<textarea id="text-adaption" class="text-adaption" rows="1"></textarea>
<script>
function $(id) {
return document.getElementById(id);
}
$("text-adaption").onkeyup = function() {
this.style.height = 'auto';
this.style.height = this.scrollHeight + "px";
}
</script>
===========================================
.text-adaption {
width: 300px;
height: 34px;
overflow: hidden;
padding: 5px 10px;
resize: none;
line-height: 24px;
font-size: 12px;
color: #666;
border: 1px solid #ccc;
outline: 0 none;
border-radius: 3px;
box-sizing: border-box;
}
<textarea id="text-adaption" class="text-adaption" rows="1" ></textarea>
<textarea class="text-adaption" rows="1" ></textarea>
<textarea class="text-adaption" rows="1" ></textarea
$(function(){
function getClass(c){
return document.getElementsByClassName(c);
}
var obj=getClass("text-adaption");
var len=obj.length;
for(var i=0;i<len;i++){
obj[i].onkeyup = function() {
this.style.height = 'auto';
this.style.height = this.scrollHeight + "px";
};
}
});
=================================================