简体   繁体   English

你如何获得文本区域中的光标位置?

[英]How do you get the cursor position in a textarea?

I have a textarea and I would like to know if I am on the last line in the textarea or the first line in the textarea with my cursor with JavaScript.我有一个 textarea,我想知道我是在 textarea 的最后一行还是 textarea 的第一行,我的光标是 JavaScript。

I thought of grabbing the position of the first newline character and the last newline character and then grabbing the position of the cursor.我想到了抓取第一个换行符和最后一个换行符的位置,然后抓取光标的位置。

var firstNewline = $('#myTextarea').val().indexOf('\n');
var lastNewline = $('#myTextarea').val().lastIndexOf('\n');

var cursorPosition = ?????;

if (cursorPosition < firstNewline)
    // I am on first line.
else if (cursorPosition > lastNewline)
    // I am on last line.
  • Is it possible to grab the cursor position within the textarea?是否可以在 textarea 中抓取光标位置?
  • Do you have a better suggestion for finding out if I am on the first or last line of a textarea?您是否有更好的建议来确定我是在 textarea 的第一行还是最后一行?

jQuery solutions preferred unless JavaScript is as simple or simpler.除非 JavaScript 如此简单或更简单,否则首选 jQuery 解决方案。

If there is no selection, you can use the properties .selectionStart or .selectionEnd (with no selection they're equal). 如果没有选择,则可以使用.selectionStart.selectionEnd属性(没有选择,它们是相等的)。

var cursorPosition = $('#myTextarea').prop("selectionStart");

Note that this is not supported in older browsers, most notably IE8-. 请注意,较旧的浏览器(最著名的是IE8-)不支持此功能。 There you'll have to work with text ranges, but it's a complete frustration. 在那里,您必须使用文本范围,但这是一个完全的挫败感。

I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. 我相信,尽管有一个库专门用于获取和设置输入元素中的选择/光标位置。 I can't recall its name, but there seem to be dozens on articles about this subject. 我不记得它的名字了,但是关于这个主题的文章似乎很多。

I've done a fair amount of work on this and posted a function for getting caret/selection position in textareas on Stack Overflow several times. 我已经做了很多工作,并多次在Stack Overflow上发布了一个函数来获取插入符/选择符在textareas中的位置。 Unlike pretty much every other code to do this out there, it works properly with line breaks in IE < 9. 不同于几乎所有其他代码都可以执行此操作,它可以与IE <9中的换行符一起正常工作。

Here's an example question with some background: 这是一个带有一些背景的示例问题:

Is there an Internet Explorer approved substitute for selectionStart and selectionEnd? 是否有Internet Explorer批准的selectionStart和selectionEnd替代品?

And here's a link to a jQuery plug-in I've written that includes this function and other selection-related textarea functions: 这是我编写的jQuery插件的链接,其中包括此函数和其他与选择相关的textarea函数:

https://github.com/timdown/rangyinputs https://github.com/timdown/rangyinputs

Here's a cross browser function I have in my standard library: 这是我标准库中的跨浏览器功能:

function getCursorPos(input) {
    if ("selectionStart" in input && document.activeElement == input) {
        return {
            start: input.selectionStart,
            end: input.selectionEnd
        };
    }
    else if (input.createTextRange) {
        var sel = document.selection.createRange();
        if (sel.parentElement() === input) {
            var rng = input.createTextRange();
            rng.moveToBookmark(sel.getBookmark());
            for (var len = 0;
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                len++;
            }
            rng.setEndPoint("StartToStart", input.createTextRange());
            for (var pos = { start: 0, end: len };
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                pos.start++;
                pos.end++;
            }
            return pos;
        }
    }
    return -1;
}

Use it in your code like this: 像这样在您的代码中使用它:

var cursorPosition = getCursorPos($('#myTextarea')[0])

Here's its complementary function: 这是它的补充功能:

function setCursorPos(input, start, end) {
    if (arguments.length < 3) end = start;
    if ("selectionStart" in input) {
        setTimeout(function() {
            input.selectionStart = start;
            input.selectionEnd = end;
        }, 1);
    }
    else if (input.createTextRange) {
        var rng = input.createTextRange();
        rng.moveStart("character", start);
        rng.collapse();
        rng.moveEnd("character", end - start);
        rng.select();
    }
}

http://jsfiddle.net/gilly3/6SUN8/ http://jsfiddle.net/gilly3/6SUN8/

Here is code to get line number and column position 这是获取行号和列位置的代码

function getLineNumber(tArea) {

    return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}

function getCursorPos() {
    var me = $("textarea[name='documenttext']")[0];
    var el = $(me).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;
    }
    var ret = pos - prevLine(me);
    alert(ret);

    return ret; 
}

function prevLine(me) {
    var lineArr = me.value.substr(0, me.selectionStart).split("\n");

    var numChars = 0;

    for (var i = 0; i < lineArr.length-1; i++) {
        numChars += lineArr[i].length+1;
    }

    return numChars;
}

tArea is the text area DOM element tArea是文本区域DOM元素

getCursorPos() function will return the cursor position in GWT getCursorPos()函数将返回GWT中的光标位置

    TextArea content = new TextArea();
    content.getCursorPos();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM