代码之家  ›  专栏  ›  技术社区  ›  Å ime Vidas Zim84

是否可以通过编程检测<input type=text>元素中的插入符号位置?

  •  1
  • Å ime Vidas Zim84  · 技术社区  · 14 年前

    假定 <input type=text> 包含数据的文本框。

    是否可以(通过JavaScript)检测文本框中文本课程的位置?

    我可以检测到箭头左键或箭头右键事件-但如何检测光标位置?

    为什么我需要这个:

    我在这里有一个动态文本框: http://vidasp.net/tinydemos/dynamic-textbox.html
    它工作得很好,但是有两种情况我想解决:

    1. 当光标位于文本框的开头并且用户按BACKSPACE时
    2. 当光标位于文本框的末尾并且用户按DELETE键时

    (在这两种情况下,文本框必须包含可观察效果的数据。)

    2 回复  |  直到 13 年前
        1
  •  3
  •   Community CDub    8 年前

    我在这方面做了很多工作。以下内容适用于所有主要浏览器(包括IE6)的文本 <input> s和 <textarea> s和将在所有情况下工作,包括有前导和尾随空格时(这是许多解决方案(包括a-tools)崩溃的地方)。这个问题中有一些代码的背景: IE's document.selection.createRange doesn't include leading or trailing blank lines

    作为我编写的jQuery input/textarea selection插件的一部分,您还可以获得以下内容,该插件尚未记录在案: http://code.google.com/p/rangyinputs/

    function getInputSelection(el) {
        var start = 0, end = 0, normalizedValue, range,
            textInputRange, len, endRange;
    
        if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
            start = el.selectionStart;
            end = el.selectionEnd;
        } else {
            range = document.selection.createRange();
    
            if (range && range.parentElement() == el) {
                len = el.value.length;
                normalizedValue = el.value.replace(/\r\n/g, "\n");
    
                // Create a working TextRange that lives only in the input
                textInputRange = el.createTextRange();
                textInputRange.moveToBookmark(range.getBookmark());
    
                // Check if the start and end of the selection are at the very end
                // of the input, since moveStart/moveEnd doesn't return what we want
                // in those cases
                endRange = el.createTextRange();
                endRange.collapse(false);
    
                if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                    start = end = len;
                } else {
                    start = -textInputRange.moveStart("character", -len);
                    start += normalizedValue.slice(0, start).split("\n").length - 1;
    
                    if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                        end = len;
                    } else {
                        end = -textInputRange.moveEnd("character", -len);
                        end += normalizedValue.slice(0, end).split("\n").length - 1;
                    }
                }
            }
        }
    
        return {
            start: start,
            end: end
        };
    }
    
    var el = document.getElementById("your_input");
    var sel = getInputSelection(el);
    alert(sel.start + ", " + sel.end);
    
        2
  •  1
  •   Oliver M Grech    14 年前

    是的,这是可能的。

    如果你用

    http://plugins.jquery.com/project/a-tools

    祝你好运:)

    编辑:请注意,光标通常被引用为“插入符号”,仅供参考;)