检测何时“输入内的光标位置改变”。在jQuery? [英] Detect when "cursor position inside input change" in jQuery?
问题描述
我正在使用一个名为 jQuery TextRange 的插件来获取光标在输入中的位置(在我的例子中,是一个textarea)并设置位置。
I'm using a plugin called jQuery TextRange to get the position of cursor inside a input (in my case, a textarea) and set the position too.
但现在我有一件事 - 我认为 - 更难解决。我想知道在jQuery中是否存在一个像光标位置已更改的事件。 我的意思是:
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:
$('#my-input').on('cursorchanged', function(e){
// My code goes here.
)};
我想知道光标在输入/文本区域内移动的时间,无论是否通过箭头键或鼠标单击。我是一个jQuery新手,但我认为在jQuery上不存在这样的事件,或者存在?
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?
推荐答案
否,没有像光标位置改变这样的事件。
No, there is no event like "cursor position changed".
但是如果你想知道光标位置是否改变了,你可以这样做:
用jquery 1.7测试,我测试了Ie8和chrome
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
var last_position = 0;
$(document.ready(function () {
$("#my_input").bind("keydown click focus", function() {
console.log(cursor_changed(this));
});
});
console.log将如果光标已更改则返回
the console.log will return if the cursor have changed
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;
}
这篇关于检测何时“输入内的光标位置改变”。在jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!