【问题标题】:Cannot set rows for textarea once you set the scrollHeight设置 scrollHeight 后无法为 textarea 设置行
【发布时间】:2016-02-09 03:38:27
【问题描述】:

经过数小时试图找出我出错的地方,我终于发现一旦为 textarea 设置了 scrollHeight,就​​无法设置 textarea 的行。为什么会发生这种情况,我们将如何解决?

<?php
include("ajaxLink.php");
?>

<textarea id = 'textarea' cols = '30' rows = '3' onkeydown = "changeIt()">
text text text text text text text text 
text text text text text text text text 
text text text text text text text text 
text text text text text text text text 
text text text text text text text text 
text text text text text text text text 
text text text text text text text text 
text text text text text text text text 
text text text text text text text text 
</textarea>

<script>

//******************************************************************

function changeIt() {

$('#textarea').height($('#textarea')[0].scrollHeight); 
document.getElementById('textarea').rows = 1000; 

} //end of function changeIt()
//******************************************************************

</script>

很明显,这不是我实际使用的函数,这里只是为了证明设置scrollHeight后设置textarea的行数不起作用。

【问题讨论】:

  • 你也可以发布html吗?
  • @user2181397 老实说,我的代码真的很长。不过别担心,我会做一个示例代码,真的很快。
  • @user2181397 我举了一个例子。
  • 你想在那里做什么?
  • @mikegohome 这只是一个例子。需要这个的实际原因:textarea 使用 scrollHeight 自动调整到内容。然后随着用户在 textarea 中输入更多文本,使用 javascript 设置行会变得更大。

标签: javascript jquery textarea


【解决方案1】:

我不确定这是否能达到您的目的,但我从 cmets 了解到您想在 keydown 时自动调整 textarea 的高度。但我不确定blur 的要求是什么。

我认为它会回到原来的高度

CSS

textarea {
    min-height: 52px;
}

JS

$("#textarea").on('keydown',function(){
        $(this).height( 0 );
        $(this).height( this.scrollHeight );
      })
    $("#textarea").on('blur',function(){
       $(this).height(0);
    })

jsfiddle demo

【讨论】:

  • 我需要 scrollHeight 和设置行。他们需要相互配合。
猜你喜欢
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多