html
<textarea id="text"></textarea>
<textarea id="shadow"></textarea>
css
#shadow, #text { font: 12px/16px Arial; width: 200px; overflow: hidden; height: 16px; }
#shadow { position: absolute; border-width: 0px; padding: 0px; visibility: hidden; }
#text { resize: none; }
js
shadow.value = text.value;
setHeight();
setTimeout(setHeight, 0); //防止ie6,7,8延迟问题
function setHeight() { text.style.height = text.scrollHeight + "px"; console.log(text.scrollHeight); }
为什么我要有一个隐藏的textArea的scrollHeight高度来代替可见的textArea的高度,这样的话高度才不会错
为什么我已经设置了position:absolute visibility:hidden 已经是不占据空间了,假若我在后面加个内联元素当textArea自适应高度的时候我这个内联元素也会被挤下去?
不是特别清楚你的问题 而且试了下代码貌似无效。 写了个简单的sample, 希望有帮助:
http://jsbin.com/bafavuhulu/1/edit?html,css,js,output
visibility:hidden虽然不可见但会占空间,display:none;才不占空间