selectionStart和selectionEnd在文本区域表示什么? [英] What do selectionStart and selectionEnd signify for textarea?

查看:454
本文介绍了selectionStart和selectionEnd在文本区域表示什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下代码片段,将enter键插入到按ctrl + enter键的文本区域中的文本中.

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

$("#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;
    }
}

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

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指定<textarea>中选择/突出显示的文本的索引.同样,selectionEnd指定选择结束的索引.最初,它们设置为0,并且如果<textarea>被聚焦但未选择任何文本,则selectionStartselectionEnd值将相同,并反映插入符在该值内的位置. <textarea>.在<textarea>处于未聚焦状态或blur时,它们将保持在blur事件之前设置的最后一个值.

selectionStart specifies the index of the selection/highlighted text within the <textarea>. Similarly, selectionEnd specifies the index where the selection ends. Initially, they are set to 0, and if the <textarea> is focused but no text is selected, the selectionStart and selectionEnd values will be the same, and reflect the position of the caret within the value of the <textarea>. On un-focus or blur of the <textarea>, they will remain at the last value that they were set to before the blur event.

这篇关于selectionStart和selectionEnd在文本区域表示什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆