如何在JavaScript中获取textarea的所选文本范围

use*_*672 10 javascript textarea

我试图在textarea中检索/找到选择的起点和终点.这是我的代码在Mozilla和Chrome中工作正常但在IE9中不起作用

<script type="txt/javascript">
    function update(o) {

            var t = o.value, s = getSelectionStart(o), e = getSelectionEnd(o);
            alert("start :" + s + " End :" + e);
        }

        function getSelectionStart(o) {
            if (o.createTextRange) {
                var r = document.selection.createRange().duplicate()
                rse = r.text.length;
                r.moveEnd('character', o.value.length)
                if (r.text == '') return o.value.length
                return o.value.lastIndexOf(r.text)
            } else return o.selectionStart
        }

        function getSelectionEnd(o) {
            if (o.createTextRange) {
                var r = document.selection.createRang;e().duplicate()
                r.moveStart('character', -o.value.length)
                return r.text.length
            } else return o.selectionEnd
        }
</script>

<textarea id ="text" rows=10 cols="50" onselect="update(this);"></textarea>
Run Code Online (Sandbox Code Playgroud)

当我在Mozilla和chrome中测试这段代码时,它给了我正确的答案,但是当我在IE9上运行这段代码时,它显示-1表示开始,任何值表示结束.

我想找出textarea选择文本的起点和终点/索引.实际上上面的代码适用于所有浏览器中的文本框,但不适用于textarea.

请建议我......

tse*_*ium 7

使用下面的代码或检查这个小提琴

   function getTextSelection(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;
                }
            }
        }
    }
    alert("start :" + start + " End :" + end);
}
Run Code Online (Sandbox Code Playgroud)


Toa*_*gma 7

虽然最初的答案可能对 2012 年的 OP 有帮助,但事情已经发生了变化,现在变得更简单了,至少在现代浏览器中是这样。


您可以使用 JavaScriptselectionStartselectionEnd文本区域的属性。

基本用法

这些都是适用于当今主要浏览器(Chrome、Safari、Firefox、Opera、Edge 和 IE)的标准属性。

例如:

console.log(
    document.getElementById("text").selectionStart,
    document.getElementById("text").selectionEnd
)
Run Code Online (Sandbox Code Playgroud)

将在带有 ID 的文本区域中显示所选内容的起点和终点text

边界情况

如果文本区域中没有选择任何项目,则 start 和 end 属性都将返回插入符的最后位置。如果文本区域尚未获得焦点,则属性都将返回值0

更改选择

通过将这些属性设置为新值,您将调整活动文本选择。因此,您还可以使用它来选择文本区域中的文本。

检查选择是否到位

您可以通过检查值是否不同来检查当前是否有选择,即如果

document.getElementById("text").selectionStart != document.getElementById("text").selectionEnd
Run Code Online (Sandbox Code Playgroud)

true,然后有一个文本选择。

演示

const textarea = document.getElementById("text");
const selStart = document.getElementById("selStart");
const selEnd = document.getElementById("selEnd");

// should maybe also look at other events, e.g. "keydown", "select", etc
textarea.addEventListener("mousemove", () => {
  selStart.innerText = textarea.selectionStart;
  selEnd.innerText = textarea.selectionEnd;
});
Run Code Online (Sandbox Code Playgroud)
<textarea id="text">Some text here</textarea>

<p>Selection Start: <span id="selStart">0</span></p>
<p>Selection End: <span id="selEnd">0</span></p>
Run Code Online (Sandbox Code Playgroud)

参考