在 jQuery 中检测“输入中的光标位置发生变化”的时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19755633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect when "cursor position inside input change" in jQuery?
提问by Paladini
I'm using a plugin called jQuery TextRangeto get the position of cursor inside a input (in my case, a textarea) and set the position too.
我正在使用一个名为jQuery TextRange的插件来获取光标在输入(在我的例子中是一个 textarea)内的位置并设置位置。
But now I have one thing that - I think - is harder to solve. I want know if in jQuery exist one event like "cursor position changed". What I mean is something like:
但现在我有一件事情——我认为——更难解决。我想知道在 jQuery 中是否存在一个像“光标位置改变”这样的事件。我的意思是这样的:
$('#my-input').on('cursorchanged', function(e){
// My code goes here.
)};
I want to know when the cursor is moved inside the input/textarea, doesn't matter if by arrow keys or mouse click. I'm a jQuery newbie, but I think doesn't exist a event like this on jQuery, or exists?
我想知道光标何时在输入/文本区域内移动,无论是通过箭头键还是鼠标单击。我是 jQuery 新手,但我认为 jQuery 上不存在这样的事件,还是存在?
回答by Renato Prado
No, there is no event like "cursor position changed".
不,没有像“光标位置改变”这样的事件。
But if you want to know if the cursor position changed, you can do something like this: tested with jquery 1.7, i tested in Ie8 and chrome
但是如果你想知道光标位置是否改变,你可以这样做:用jquery 1.7测试,我在Ie8和chrome中测试过
var last_position = 0;
$(document.ready(function () {
$("#my_input").bind("keydown click focus", function() {
console.log(cursor_changed(this));
});
});
the console.log will return if the cursor have changed
如果光标发生变化,console.log 将返回
function cursor_changed(element) {
var new_position = getCursorPosition(element);
if (new_position !== last_position) {
last_position = new_position;
return true;
}
return false;
}
function getCursorPosition(element) {
var el = $(element).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;
}
回答by jcubic
I needed something like this myself, so based on @RenatoPrado solution I've created a jQuery extension (it's on npm - jquery-position-event).
我自己需要这样的东西,所以基于@RenatoPrado 解决方案,我创建了一个 jQuery 扩展(它在 npm - jquery-position-event 上)。
To use it you can add standard event:
要使用它,您可以添加标准事件:
var textarea = $('textarea').on('position', function(e) {
console.log(e.position);
});
and if you want the initial value you can use:
如果你想要初始值,你可以使用:
var textarea = $('textarea').on('position', function(e) {
console.log(e.position);
}).trigger('position');
The event also have useful column and line properties.
该事件还具有有用的列和行属性。