简体   繁体   English

textarea.selectionEnd 总是等于 textarea.value 中的最后一个字符

[英]textarea.selectionEnd is always equal to the last character in textarea.value

        function makeBold() {
            ta = document.getElementById('instructions');
            if (ta.selectionStart != ta.selectionEnd) {
                ta.value = [ta.value.slice(0, ta.selectionStart), '<strong>', ta.value.slice(ta.selectionStart)].join('');
                ta.value = [ta.value.slice(0, ta.selectionEnd), '</strong>', ta.value.slice(ta.selectionEnd)].join('');
            }
        }

I wrote this function that gets triggered by an on_click event for a button.我写了这个由按钮的on_click事件触发的 function。 .selectionStart returns the start of the selected text but .selectionEnd is always returning the last character of the textearea's value, not the index where the selected text ends. .selectionStart返回所选文本的开头,但.selectionEnd始终返回 textearea 值的最后一个字符,而不是所选文本结束的索引。

I tested this with:我对此进行了测试:

                console.log(ta.selectionEnd, ta.value.length)

and they both return the same.他们都返回相同的。

Can anyone help me see what I am misunderstanding here?谁能帮我看看我在这里误解了什么?

Bit of a rubber duck moment.有点橡皮鸭的时刻。

I have solved this with the code:我已经用代码解决了这个问题:

        function makeBold() {
            ta = document.getElementById('instructions');
            const start = ta.selectionStart;
            const end = ta.selectionEnd;
            if (ta.selectionStart != ta.selectionEnd) {
                ta.value = [ta.value.slice(0, start), '<strong>', ta.value.slice(start)].join('');
                ta.value = [ta.value.slice(0, end+8), '</strong>', ta.value.slice(end+8)].join('');
            }
        }

I suspect editing the textarea's value removed the current selection, so I captured the start and end of the selection first, then make the edits.我怀疑编辑 textarea 的值会删除当前选择,所以我先捕获了选择的开始和结束,然后进行编辑。 I also add 8 to the value of.selectionEnd to account for the 8 characters in ''.我还将 8 加到 .selectionEnd 的值以说明 '' 中的 8 个字符。

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

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