在文本区域中获取换行符

Getting line breaks in a text area

我想为文本区域中的电子邮件创建提前输入机制。

如果我在文本区域中键入内容,控件会自动将文本自动换行,所以我知道光标当前的位置(即它的 x,y 位置)取决于这些换行符发生的位置。 (选择位置就是光标所在位置距离开始多少个字符。)

我需要 x 任何 y 位置,以便我可以在光标下方放置一个可能完成的列表。

有没有办法从控件中提取此换行符信息,或者我是否必须修改它并执行 "roll your own" 文本换行算法(这很棘手,因为它不容易测量文本宽度 javascript.)

如有任何帮助,我们将不胜感激。

将所有内容与 jQuery 放在一起。如果您需要 JavaScript 块,请告诉我。

$(function() {
  var textProps = [0, 0];
  $("textarea.allow-overflow").keyup(function(e) {
    var self = $(this);
    var text_width = $(".hidden").text(self.val()).css({
      'font-weight': self.css("font-weight"),
      'font-size': self.css("font-size"),
      'font-family': self.css("font-family"),
      'white-space': 'nowrap',
      'position': 'absolute',
      'display': 'block',
      'width': 'auto'
    }).hide().width();
    textProps[0] = $(".hidden").width();
    textProps[1] = $(".hidden").height();
    var overflows = text_width > self.width();
    var lines = 1;
    if (overflows) {
      lines = Math.floor(self.prop("scrollHeight") / $(".hidden").height());
      textProps[0] = textProps[0] - (self.width() * (lines - 1));
      textProps[1] = $(".hidden").height() * lines;
    }
    $(".report").html("X (Left): " + textProps[0] + "px, Y (Top): " + textProps[1] + "px, Wrap: " + overflows.toString() + ", Lines: " + lines);
  });
});
.widget label {
  display: block;
}

.widget .allow-overflow,
.report {
  width: 240px;
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
  font-size: 13px;
  font-weight: 400;
}

.report {
  border: 1px dashed #ccc;
  font-size: 9px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
  <label>Type in me</label>
  <textarea class="allow-overflow"></textarea>
</div>
<div class="report">&nbsp;</div>
<div class="hidden"></div>

我们需要了解一些事情。

  1. 当我们溢出并在文本框中换行时。
  2. 文本框的宽度和字体属性
  3. 文字的行高

然后我们可以从文本框的[X (Left), Y (Top)]计算出当前光标的位置。当我们输入文本时,它会增加隐藏的 div.

widthheight

在第一行,这很简单,x = widthy = height。换行后,我们现在必须计算偏移量和行数。

number of lines = floor( text box scroll height / hidden height )
x pos on line = hidden width - (width of text box * number of lines)
y pos = line height * number of lines

您可以将其推送到一个函数中,并将结果数据清​​理到一个数组或对象中。

如果允许调整大小,那么我们不能指望文本框的静态宽度和高度。所以,对于我的例子,我每次都抓住那个细节。

希望对您有所帮助。