以前在公司作项目的时候,有这么一个需求,要我写一个评论框,能够随着评论的行数增长而自动扩大,最开始我想用textarea实现,可是后来尝试后发现textarea并不适合,textarea的高度不会随着输入行数的增多而增大,因而我上网寻求了下帮助,发现大神张鑫旭的这篇文章《div模拟textarea文本域轻松实现高度自适应》,成功解决个人问题javascript
代码以下:css
1 1 <!DOCTYPE html> 2 2 <html lang="en"> 3 3 <head> 4 4 <meta charset="UTF-8"> 5 5 <title>div模拟textarea自适应高度le> 6 6 <style type="text/css"> 7 7 .test_box{ 8 8 width:500px; 9 9 min-height:200px; 10 10 max-height:600px; 11 11 _height:200px;/*兼容IE6浏览器*/ 12 12 margin:0 auto; 13 13 padding:3px; 14 14 outline:0; 15 15 border:1px solid #e4e4e4; 16 16 font-size:12px; 17 17 word-wrap:break-word;/*用于英文文本自动换行,全部主流浏览器支持*/ 18 18 overflow-x:hidden; 19 19 overflow-y:auto; 20 20 -webkit-user-modify: read-write-plaintext-only; 21 21 } 22 22 </style> 23 23 </head> 24 24 <body> 25 25 <div class="test_box" contenteditable="true">我是模拟textarea的div</div> 26 26 <script type="text/javascript"> 27 27 if (typeof document.webkitHidden == "undefined") { 28 28 // 非chrome浏览器阻止粘贴 29 29 box.onpaste = function() { 30 30 return false; 31 31 } 32 32 } 33 33 </script> 34 34 </body> 35 35 </html>
其中有一两个从没见过的属性:html
read-only | 内容只读。 |
---|---|
read-write | 内容可读写。 |
read-write-plaintext-only | 内容可读写,但粘贴内容中的富文本格式(如文本的颜色、大小,图片等)会丢失。内容相似于以纯文本显示。 |
true | 规定能够编辑元素内容。 |
---|---|
false | 规定没法编辑元素内容。 |
再次感谢鑫大神(http://www.zhangxinxu.com/),分享了好多很是实用的经验,等未来能达到他那种高度,我也想写出好博客分享出来造福人类,哈哈,虽然还很遥远,继续fighting~java