Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

javascript - Detect when "cursor position inside input change" in jQuery?

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.

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.
)};

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

var last_position = 0;
$(document).ready(function () {
    $("#my_input").bind("keydown click focus", function() {
        console.log(cursor_changed(this));
    });
});

the console.log will return when 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...