获取插入符号位置的常见解决方案会返回奇怪的结果
Common solution to get caret position returns weird results
我正在尝试获取文本区域中的插入符号位置。我使用了很多不同的方法,其中大多数都涉及到获取范围或获取元素的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都能正常工作。
这能回答您的问题吗?
纯JS:https://stackoverflow.com/a/1891501/671373
jQuery:https://stackoverflow.com/a/1909997/671373
否则,您可能会选中"jQuery-fieldSelection"
https://github.com/localhost/jquery-fieldselection
从其描述来看:"一个jQuery插件,用于获取'设置插入符号/选择。"
- JSONP请求返回结果,但也触发error_callback
- async问题,JS Promise无法返回结果,但可以使用console.log
- Meteor js-控制台显示'未定义'即使返回结果
- 正在等待HTTP调用从函数返回结果
- 使用函数for循环遍历对象以更改值,然后返回结果
- 迭代 JSON 文件并且未在 Javascript 中正确返回结果
- Javascript 函数不返回结果
- 用逗号分隔返回结果中的对象
- 需要呈现MongoDB查询返回结果的特定索引/位置
- HTML5 文件阅读器如何返回结果
- javascript循环遍历列表项,并在数组中返回结果
- 使用jquery UI next按钮提交输入字段值,php将返回结果
- 在angularjs工厂中,如何在函数解析后返回结果
- 我在jQuery中的Rock Paper Scissors程序只在平局时返回结果
- 如何使用ajax调用php并返回结果
- 添加第二维度的Javascript未返回结果
- Node.js没有返回结果
- jquery裁剪图像selction未返回结果
- 如何在phonegap javascript函数中返回结果
- 如果文本筛选器在ng重复中未返回结果,则显示消息