textarea高度自適應函式
阿新 • • 發佈:2018-11-11
在實現textarea根據內容的增多實現高度自適應,且無滾動條的效果,方法有2種。
第一種方法:通過事件onkeyup來實現這樣的效果
備註:onkeyup事件發生階段
1、onkeyup事件會在鍵盤按鍵被鬆開時發生;
2、與onkeyup事件相關的事件發生次序:
1)onkeydown----------鍵盤按下------------------------------------------------所有瀏覽器都支援
2)onkeypress---------鍵盤按鍵被按下並釋放一個鍵時發生----------不是適用於所有按鍵(如: ALT, CTRL, SHIFT, ESC)
3)onkeyup ----------鍵盤被鬆開-----------------------------------------------都支援
程式碼如下:
<p>方法一:onkeyup事件</p> <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>
效果圖:
高度會隨著內容的增加而增加,但是每次高度的增加都會帶來整體高度的輕微顫動,視覺效果不是很好。
第二種方法:通過oninput事件實現效果,支援冒泡
程式碼如下:
<p>方法二:oninput事件</p> <textarea id="testHeight" oninput="autoHeight()"></textarea> <script> // 法二 function autoHeight(){ var x = document.getElementById("testHeight"); x.style.height = 'auto'; x.style.height = x.scrollHeight + "px"; } </script>
效果圖:
實現了高度隨內容的增高而增高,且在高度增高的過程中,整體自然增高,無抖動現象出現,視覺效果完美。
方法一與方法二的樣式如下:
<style type="text/css">
textarea {
resize: none;
}
.text-adaption {
width: 300px;
height: 34px;
overflow: hidden;
resize: none;
line-height: 24px;
font-size: 12px;
color: #666;
border: 1px solid #ccc;
outline: 0 none;
border-radius: 3px;
box-sizing: border-box;
}
</style>