在文本区域中获取换行符



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

如果我在文本区域中键入,控件将自动对文本进行自动换行,因此对我来说,知道光标当前的位置(即其 x,y 位置(取决于这些换行符发生的位置。(选择位置只是光标从开头开始的字符数。

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

有没有办法从控件中提取此换行符信息,或者我是否必须修改它并执行"滚动自己的"文本换行算法(这很棘手,因为在 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

您可以将其推送到函数中,并将生成的数据清理到数组或对象中。

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

希望有帮助。

最新更新