【问题标题】:Get keyup position using jquery [duplicate]使用jquery获取keyup位置[重复]
【发布时间】:2012-09-29 11:49:22
【问题描述】:

可能重复:
How to get caret position in textarea?

如果我在 html textarea 控件的任何位置键入 *,我需要获取 keyup 事件的当前位置,例如 "Welcome* to jQuery"。所以我在欢迎之后有 * 意味着在第 8 位。让我知道是否有人可以帮助我。

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    这会奏效。 (注意:带引号的是 8 点,否则是 7 点)

    $("#tf").on('keyup', function(){
        console.log($(this).val().indexOf('*'));
    });​
    

    http://jsfiddle.net/Vandeplas/hc6ZH/

    更新: 具有多个 * 的解决方案

    $("#tf").on('keyup', function(){
        var pos = [],
            lastOc = 0,
            p = $(this).val().indexOf('*',lastOc);
    
        while( p !== -1){
            pos.push(p);
            lastOc = p +1;
            p = $(this).val().indexOf('*',lastOc);
        }
        console.log(pos);
    });​
    

    http://jsfiddle.net/Vandeplas/hc6ZH/1/

    更新:只给出您刚刚输入的 * 字符的位置

    (function ($, undefined) {
        $.fn.getCursorPosition = function() {
            var el = $(this).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);
    
    $("#tf").on('keypress', function(e){
        var key = String.fromCharCode(e.which);
        if(key === '*') {
            var position = $(this).getCursorPosition();
            console.log(position);
        } else {
            return false;
        }
    });​
    

    http://jsfiddle.net/Vandeplas/esDTj/1/

    【讨论】:

    • 如果按两次 * 会怎样?那么你只会得到第一个的索引。
    • @MiniGod 是对的。我需要 * 的位置来触发 keyup 事件而不是其他事件。
    • 不知道需要我更新;)
    • 您的答案只列出了所有出现的*?这个jsfiddle.net/esDTj怎么样
    【解决方案2】:

    以下链接帮助我使用 jQuery 本身解决了这个问题。

    Cursor position in a textarea (character index, not x/y coordinates)

    感谢你们的努力。

    【讨论】:

    • 哎呀,误解了这个问题。现在我看到了你需要什么 ;) 好 4 你!干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 2011-12-08
    相关资源
    最近更新 更多