我想为文本区域中的电子邮件创建一个提前类型的机制。
如果我键入一个文本区域,该控件将自动对文本进行文字包装,因此我要知道光标当前的位置(即它的x,y位置)取决于这些换行符发生的位置。(选择的位置是光标起始处的字符数。)
我需要x任意y位置,这样我就可以在光标下方定位一个可能完成的列表。
是否有一种方法从控件中提取此行中断信息,或者我是否必须修改它并执行“自己的”文本包装算法(这很棘手,因为在javascript中测量文本宽度并不容易)。
任何帮助都将不胜感激。
发布于 2018-05-01 07:06:22
把所有的东西和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"> </div>
<div class="hidden"></div>
我们需要知道一些事情。
然后,我们可以从文本框的[X (Left), Y (Top)]
中计算当前光标的位置。当我们输入文本时,它会增加隐藏div的width
和height
。
在第一行,这很简单,x
= width
和y
= 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
您可以将其推入函数中,并将结果数据清除到数组或对象中。
如果允许调整大小,则不能指望文本框的静态宽度和高度。所以,作为我的例子,我每次都会抓住这个细节。
希望这能有所帮助。
https://stackoverflow.com/questions/50111568
复制相似问题