javascript selectionStart 和 selectionEnd 对 textarea 意味着什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28663249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:20:24  来源:igfitidea点击:

What do selectionStart and selectionEnd signify for textarea?

javascriptjqueryhtml

提问by vjain27

I came across following code snippet to insert enter into the the text in a textarea where ctrl + enter is pressed.

我遇到了以下代码片段,将 enter 插入到按下 ctrl + enter 的 textarea 中的文本中。

$("#txtChatMessage").keydown(MessageTextOnKeyEnter);
function MessageTextOnKeyEnter(e) {
    console.log(this.selectionEnd);
    if (e.keyCode == 13) {
        if (e.ctrlKey) {
            var val = this.value;
            if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
                var start = this.selectionStart;

                this.value = val.slice(0, start) + "\n" + val.slice(this.selectionEnd);
                this.selectionStart = this.selectionEnd = start + 1;
            } else if (document.selection && document.selection.createRange) {
                this.focus();
                var range = document.selection.createRange();
                range.text = "\r\n";
                range.collapse(false);
                range.select();
            }
        }
        return false;
    }
}

What I don't understand is what do selectionStart and selectionEnd mean here ? According to documentation that I read, selectionStart-End contain the start-end of selected text in the input element. However, here no text is explicitly selected. On doing console.log I could see that both these properties always have some value even when the text is not selected. Why is that?

我不明白的是 selectionStart 和 selectionEnd 在这里是什么意思?根据我阅读的文档, selectionStart-End 包含输入元素中所选文本的开始结束。但是,这里没有明确选择文本。在执行 console.log 时,我可以看到即使未选择文本,这两个属性也始终具有某些值。这是为什么?

回答by andrewgu

selectionStartspecifies the index of the selection/highlighted text within the <textarea>. Similarly, selectionEndspecifies the index where the selection ends. Initially, they are set to 0, and if the <textarea>is focused but no text is selected, the selectionStartand selectionEndvalues will be the same, and reflect the position of the caret within the value of the <textarea>. On un-focus or blurof the <textarea>, they will remain at the last value that they were set to before the blurevent.

selectionStart指定 中选择/突出显示的文本的索引<textarea>。同样,selectionEnd指定选择结束的索引。最初,它们被设置为0,如果<textarea>聚焦但未选择文本,则selectionStartselectionEnd值将相同,并反映插入符号在 值内的位置<textarea>。在 un-focus 或blurof 时<textarea>,它们将保持在blur事件之前设置的最后一个值。

回答by Marc

Here's a fiddle you can play with: http://jsfiddle.net/5vd8pxct/

这是你可以玩的小提琴:http: //jsfiddle.net/5vd8pxct/

The ifblock in question appears to handle cross-browser compatibility. document.selectionis for IE. selectionStartand selectionEndseem to work elsewhere. I don't have IE on my machine to experiment with it, and I'm using Chrome. It appears from my fiddle that the default start/end are 0when the page loads. If you click into/select in the box, the start end will be as expected. If you click outside the box, the positions within the box are remembered.

if有问题的块似乎处理跨浏览器兼容性。 document.selection是为IE。 selectionStart并且selectionEnd似乎在其他地方工作。我的机器上没有 IE 来试验它,我正在使用 Chrome。从我的小提琴看来,默认的开始/结束时间是0页面加载时。如果您在框中单击进入/选择,则开始结束将如预期的那样。如果您在框外单击,则会记住框内的位置。

document.selectionis undefined in Chrome.

document.selection在 Chrome 中未定义。

回答by seboettg

Your code does not work. You mix regular JavaScript and JQuery. I would suggest to start with plain JavaScript. Generally, in JavaScript thisis a reference to the object on which the code will be executed.

您的代码不起作用。您将常规 JavaScript 和 JQuery 混合使用。我建议从纯 JavaScript 开始。通常,在 JavaScript 中this是对将执行代码的对象的引用。

Take a look at the following example:

看看下面的例子:

<html>
<head>
    <script type="text/javascript">
        window.addEventListener("load", function () {
            var chat = document.getElementById('txtChatMessage'); // get textarea

            chat.addEventListener('keydown', function (event) { //add listener keydown for textarea

                event = event || window.event;

                if (event.keyCode === 13) {  //return pressed?
                    event.preventDefault();
                    if (this.selectionStart != undefined) {
                        var startPos = this.selectionStart;
                        var endPos = this.selectionEnd;
                        var selectedText = this.value.substring(startPos, endPos);
                        alert("Hello, you've selected " + selectedText);
                    }
                }
                
            })
        });
    </script>
</head>

<body>
    <textarea id="txtChatMessage" cols="40" rows="10"></textarea>
</body>
</html>

At first an event listener "onLoad" has been registered. Within this function we get a reference to the textarea object. On this object a new event listener "onKeyDown" has been registered. Within this function thisrefers to the textarea (chat) object. With the help of the eventobject, we can ask for the pressed key event.keyCode === 13. With this(textarea) and its attributes selectionStartand selectionEndwe get the selected text.

首先注册了一个事件监听器“onLoad”。在这个函数中,我们获得了对 textarea 对象的引用。在这个对象上注册了一个新的事件监听器“onKeyDown”。在这个函数this中指的是 textarea( chat) 对象。在event对象的帮助下,我们可以要求按下的键event.keyCode === 13。使用this(textarea) 及其属性selectionStartselectionEnd我们得到选定的文本。