检测“输入中光标位置改变"的时间在 jQuery 中? [英] Detect when "cursor position inside input change" in jQuery?

查看:14
本文介绍了检测“输入中光标位置改变"的时间在 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 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;
}

这篇关于检测“输入中光标位置改变"的时间在 jQuery 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆