textarea的scrollheight问题不一致

时间:2015-08-12 14:56:55

标签: javascript html textarea

这个问题不容易解释,所以如果这个问题看起来很混乱我会道歉。

基本上,我有<textarea>根据其值改变身高。如果存在任何垂直溢出(通常会产生垂直滚动条),我会增加<textarea>的高度以匹配其scrollHeight属性。这似乎对前两行很好,但是当添加更多文本时,我注意到scrollHeight增加的点对于每行文本都是不同的。

这是一个演示奇怪行为的小提琴:http://jsfiddle.net/2zpkf6fL/2/

键入大约5或6行文字,你会看到我在说什么。

有人能解释一下这个问题吗?为什么scrollHeight在不同的文本行的不同点增加?

1 个答案:

答案 0 :(得分:1)

以下是我如何做你想做的事。

HTML:

    <div class="textarea-container">
  <textarea></textarea>
  <div class="textarea-size"></div>
</div>

CSS:

.textarea-container {
  position: relative;
  /* you should change this*/
  width: 50%;
}

textarea, .textarea-size {
  min-height: 25px;
  /* need to manually set font and font size */
  font-family: sans-serif;
  font-size: 14px;
  box-sizing: border-box;
  padding: 4px;
  border: 1px solid;

  overflow: hidden;
  width: 100%;
}

textarea {
  height: 100%;
  position: absolute;
  resize:none;

  /*
  "pre" or "preline" or "normal" fixes Chrome issue where
    whitespace at end of lines does not trigger a line break.
  However, it causes the text to exhibit the behavior seen with
    "pre" that is described below.
   */
  white-space: normal;
}

.textarea-size {
  visibility: hidden;

  /*
  Pre-wrap: preserve spacing and newlines, but wrap text.
  Pre: preserve spacing and newlines but don't wrap text.

  "pre" does not wrap well on Firefox, even with word-wrap:break-word.
  "pre" on Chrome works with word-wrap, but exhibits different behavior:
  Instead of entire words being moved to the next line for wrapping,
  the browser will cut words in the middle for wrapping.
  "pre-line" has Firefox issues
  */
  white-space: pre-wrap;
  /* Required for wrapping lines in Webkit,
    but not necessary in Firefox if you have white-space wrapping
    (pre-wrap, normal, pre-line) already set */
  word-wrap: break-word;
  overflow-wrap: break-word;
}

SCRIPT:

var textContainer, textareaSize, input;
var autoSize = function () {
  textareaSize.innerHTML = input.value + '\n';
};

document.addEventListener('DOMContentLoaded', function() {
  textContainer = document.querySelector('.textarea-container');
  textareaSize = textContainer.querySelector('.textarea-size');
  input = textContainer.querySelector('textarea');

  autoSize();
  input.addEventListener('input', autoSize);
});

这是jsfiddle