【问题标题】:How can I stop text area growing beyond length of the screen?如何阻止文本区域超出屏幕长度?
【发布时间】:2016-04-22 13:45:01
【问题描述】:

我有 jQuery 代码,当用户在其中键入时,我可以使用它来自动调整 textarea 的大小。有没有办法让它在到达屏幕底部时停止?

<html>
<head>
    <title>Page Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">    </script>
</head>
<style>
    .modalTextArea{
        overflow: hidden;
        z-index: 1; 
    }
</style>
<body>
    <div class="modal-content">          
        <textarea class='modalTextArea' rows = 2 style='width: 100%'></textarea>
    </div>
    <script src = 'js/script.js'></script>
</body>
</html>
$('.modalTextArea').on('keyup', function(e){
    $(this).css('height', 'auto');
    $(this).height(this.scrollHeight + 10);
});

【问题讨论】:

  • 仅供参考,您的&lt;style&gt; 元素应该在&lt;head&gt;
  • 每次用户按键时它都会增长,这很奇怪
  • 它只会在滚动高度发生变化时增长,即当按下 Enter 或文本移动到新行时
  • @gurvinder372 - 分配固定值的唯一方法是什么?有什么方法可以动态地找出屏幕的结束位置并让它停在那里?抱歉,如果这听起来很疯狂,我对此一无所知,我只是想弄清楚什么可以做,什么不能做。谢谢

标签: javascript jquery


【解决方案1】:

我建议计算 textarea 中一行的行高,并在 keyup 事件中使用这个值:

function getTextAreaLineHeight(className) {
  var element = $('.' + className);
  var txtSaved = element.text();
  var lineHeight = element.css('font-size', '12px').css('line-height', '1.25').text('x').height();
  element.text(txtSaved);
  return lineHeight;
}

$(function () {
  var txtAreaLineHeight = getTextAreaLineHeight('modalTextArea');
  $('.modalTextArea').on('keyup', function(e) {
    if (($(this).offset().top + $(this).height()) < ($(window).height() - txtAreaLineHeight)) {
      $(this).css('height', 'auto');
      $(this).height(this.scrollHeight + 10);
    }
  });
});
.modalTextArea{
  overflow: hidden;
  z-index: 1;
}
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>

<div class="modal-content">
    <textarea class='modalTextArea' rows = 2 style='width: 100%'></textarea>
</div>

【讨论】:

    【解决方案2】:

    为了得到height of HTML document,可以使用下面的sn-p:

    $( document ).height();
    

    随着每次按下回车键时 textarea 的大小都会增加,html 的高度也会增加。所以你需要做的只是获取初始的 html 高度,换句话说,在你的事件处理程序之外,然后使用 if 子句:

    var htmlHeight = $( document ).height();
    
    $('.modalTextArea').on('keyup', function(e){
        var elementHeight = this.scrollHeight;
        if( htmlHeight > elementHeight ) {
          $(this).css('height', 'auto');
          $(this).height(this.scrollHeight +10);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      • 1970-01-01
      • 2017-07-08
      • 2021-10-13
      相关资源
      最近更新 更多