我需要根据内容增加文本区域的高度。如果用户键入内容,它会自动增加。如果删除内容,则需要降低高度。
答案 0 :(得分:2)
是的,我得到了答案,工作正常。
<textarea onkeyup="textAreaAdjust(this)" placeholder="Add a new answer" rows="1"></textarea>
<script type="text/javascript">
function textAreaAdjust(o) {
o.style.height = "1px"; o.style.height = (25+o.scrollHeight)+"px"; }
</script>
答案 1 :(得分:1)
试试这个:
<script type="text/javascript">
var observe;
if (window.attachEvent) {
observe = function (element, event, handler) {
element.attachEvent('on'+event, handler);
};
}
else {
observe = function (element, event, handler) {
element.addEventListener(event, handler, false);
};
}
function init () {
var text = document.getElementById('text');
function resize () {
text.style.height = 'auto';
text.style.height = text.scrollHeight+'px';
}
/* 0-timeout to get the already changed text */
function delayedResize () {
window.setTimeout(resize, 0);
}
observe(text, 'change', resize);
observe(text, 'cut', delayedResize);
observe(text, 'paste', delayedResize);
observe(text, 'drop', delayedResize);
observe(text, 'keydown', delayedResize);
text.focus();
text.select();
resize();
}
</script>
<body onload="init();">
<textarea rows="1" style="height:1em;" id="text"></textarea>
</body>
</html>
&#13;
这是Demo
答案 2 :(得分:1)