我正在尝试获取文本区域中的插入符位置。我使用了很多不同的方法,大多数涉及获取范围或获取元素的 SelectionStart 。由于某种原因,虽然它在某种程度上有效,但每当我仍在输入新字符并且尚未插入任何字符时,它会返回比应有的值少的一个。
例如:给定以下输入,插入符号为|:
| : 0
a| : 1
ab| : 1 <- weird!
abc| : 2 <- still weird
ab| : 2 <- back to normal
abc| : 2 <- back to weird
ad|bc : 2 <- normal
adbce| : 5 <- now normal
我想我不确定它什么时候会发生——如果你输入了一些字符但没有插入到字符串的中间,那么它似乎会少一个,之后它又开始工作.
为什么第二个字符没有添加到插入符号位置?还有其他人发现这个吗?
编辑:它在“输入”事件上运行:
// use a solution from stack that works with jquery:
(function ($, undefined) {
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
} else if('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
$(window).load(function(){
// when editing the query box
$("#query_textarea").bind('input', function(){
window.status=$("#query_textarea").getCaretPosition();
// do some other stuff
}
}
我在 Mac 上运行 Chrome
最佳答案
在使用旧版基于 webkit 的浏览器开发嵌入式设备时,我遇到了同样的问题。这是调度事件和更新控件的时间安排的问题。在事件处理程序中,我检查字段值的长度和插入符号位置,在字段中输入时它们并不相同。据我所知,这个问题已于 2013 年中期在 webkit 中得到修复。引用:https://bugs.webkit.org/show_bug.cgi?id=110742
Edge、最近的 Safari、Firefox、Chrome 均按预期工作。
关于javascript - 获取插入符号位置的常见解决方案会返回奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17457389/