1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > html textarea文本域高度自适应

html textarea文本域高度自适应

时间:2019-03-22 18:21:26

相关推荐

html  textarea文本域高度自适应

1、可直接在 菜鸟教程网站测试页面中测试

<!DOCTYPE html><html><head><meta charset="utf-8"><script src="/jquery/1.9.0/jquery.js"></script><title>菜鸟教程()</title></head><body><textarea style="width: 200px;padding:0px;"id="symptomTxt"oninput="autoTextAreaHeight(this)"></textarea></body><script type="text/javascript">//文本域自适应function autoTextAreaHeight(o) {o.style.height = o.scrollTop + o.scrollHeight + "px";} $(function () {var ele = document.getElementById("symptomTxt");autoTextAreaHeight(ele);}) </script></html>

2、其实这个段代码有些小瑕疵,输入的时候,高度自适应,但是足字删除输入的内容时,高度就不自适应了

本人改进办法,由于时间仓促,可能不是很好,如果你有好的方式,可以告诉我,在这里谢谢了。

解决:因为文本域宽度200px,测试了下,每行能输入15个汉字,length长度为30。所以我监听输入的长度,当大于30时就追加文本域高度。

<!DOCTYPE html><html><head><meta charset="utf-8"><script src="/jquery/1.9.0/jquery.js"></script><title>菜鸟教程()</title></head><body><textarea style="width: 200px;padding:0px;"id="symptomTxt"oninput="autoTextAreaHeight(this)"></textarea></body><script type="text/javascript">//获取文本长度,一个汉字长度为2var strLength = {};strLength.GetLength = function(str) {return str.replace(/[\u0391-\uFFE5]/g,"aa").length; //先把中文替换成两个字节的英文,在计算长度};//文本域自适应function autoTextAreaHeight(o) {var element = $(o).val();var len = strLength.GetLength(element);var rows = Math.ceil(len/30); o.style.height = o.scrollTop + 30 + (rows>0?rows-1:rows)*10 + "px";//o.style.height = o.scrollTop + o.scrollHeight + "px";} $(function () {var ele = document.getElementById("symptomTxt");autoTextAreaHeight(ele);}) </script></html>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。