【问题标题】:How to change height of text area like facebook in javascript?如何在javascript中更改像facebook这样的文本区域的高度?
【发布时间】:2013-12-31 02:25:19
【问题描述】:
我正在做 Facebook 之类的评论文本区域。我试图通过计算列和值的长度来做到这一点。但是符号(“l”或“a”)的大小不同。我怎样才能在javascript中做像Facebook这样的文本区域而不使用任何插件?
我的代码是这样的:
<textarea cols="50" rows="1" onkeydown="comChangeHeight(this);"></textarea>
<script type="text/javascript">
function comChangeHeight(obj) {
var id = obj.id;
var length - obj.value.length;
obj.rows = Math.ceil(length / obj.cols);
}
</script>
【问题讨论】:
标签:
html
facebook
comments
textarea
【解决方案1】:
我写了这段代码:
window.onload = function() {
var t = document.getElementsByTagName('textarea')[0];
var offset= !window.opera ? (t.offsetHeight - t.clientHeight) : (t.offsetHeight + parseInt(window.getComputedStyle(t, null).getPropertyValue('border-top-width'))) ;
var resize = function(t) {
t.style.height = 'auto';
t.style.height = (t.scrollHeight + offset ) + 'px';
}
t.addEventListener && t.addEventListener('input', function(event) {
resize(t);
});
t['attachEvent'] && t.attachEvent('onkeyup', function() {
resize(t);
});
}
我认为这对其他人也有帮助。