Pal*_*ini 15 javascript jquery input
我正在使用一个名为jQuery TextRange的插件来获取光标在输入中的位置(在我的例子中,是一个textarea)并设置位置.
但现在我有一件事 - 我认为 - 更难解决.我想知道在jQuery中是否存在一个像"光标位置已更改"的事件.我的意思是:
$('#my-input').on('cursorchanged', function(e){
// My code goes here.
)};
Run Code Online (Sandbox Code Playgroud)
我想知道光标在输入/文本区域内移动的时间,无论是通过箭头键还是鼠标单击都无关紧要.我是一个jQuery新手,但我认为在jQuery上不存在这样的事件,或者存在?
Ren*_*ado 19
不,没有像"光标位置改变"这样的事件.
但是如果你想知道光标位置是否改变了,你可以这样做:用jquery 1.7测试,我在Ie8和chrome中测试过
var last_position = 0;
$(document.ready(function () {
$("#my_input").bind("keydown click focus", function() {
console.log(cursor_changed(this));
});
});
Run Code Online (Sandbox Code Playgroud)
如果光标已更改,则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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18667 次 |
| 最近记录: |