我正在使用一个名为jQuery TextRange的插件来获取输入中光标的位置(在我的情况下为textarea)并设置位置。
但是现在我有一件事情-我认为-很难解决。我想知道jQuery中是否存在一个类似“光标位置已更改”的事件。我的意思是这样的:
$('#my-input').on('cursorchanged', function(e){
// My code goes here.
)};
我想知道何时在输入/文本区域内移动光标,无论是通过箭头键还是单击鼠标都没有关系。我是jQuery新手,但我认为在jQuery上不存在这样的事件,或者存在吗?
不,没有像“光标位置更改”这样的事件。
但是,如果您想知道光标位置是否已更改,可以执行以下操作:使用jQuery 1.7测试,我在IE8和chrome中进行了测试
var last_position = 0;
$(document).ready(function () {
$("#my_input").bind("keydown click focus", function() {
console.log(cursor_changed(this));
});
});
更改光标后,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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句