有時候我們需要textarea的高度隨著內容的多少去自適應的變化,今天我使用了JS原生和JQ寫了一個textarea的高度隨著他的內容高度變化的代碼,希望能幫上忙。
廢話不多說直接貼代碼:
textarea{ width:500px; margin:20px auto; padding:0; font-size:14px; color:#333; font-family:"Microsoft YaHei"; line-height:28px;}
CGLweb前端 http://cenggel.com/
青格勒前端博客 http://cenggel.com/
CGLweb前端 http://cenggel.com/
青格勒前端博客 http://cenggel.com/
$(document).ready(function () {
var text_box = $('#textarea');
function cglHeight() {
var cglTextHeight = text_box.get(0).scrollHeight;
text_box.css('height',cglTextHeight+'px');
console.log(cglTextHeight);
};
cglHeight();
text_box.on('keyup mousedown mouseup focus blur',function(){
cglHeight();
});
});
在線演示
如果對你有幫助,別了分享哦。