[英]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('');
}
}
我写了这个由按钮的on_click
事件触发的 function。 .selectionStart
返回所选文本的开头,但.selectionEnd
始终返回 textearea 值的最后一个字符,而不是所选文本结束的索引。
我对此进行了测试:
console.log(ta.selectionEnd, ta.value.length)
他们都返回相同的。
谁能帮我看看我在这里误解了什么?
有点橡皮鸭的时刻。
我已经用代码解决了这个问题:
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('');
}
}
我怀疑编辑 textarea 的值会删除当前选择,所以我先捕获了选择的开始和结束,然后进行编辑。 我还将 8 加到 .selectionEnd 的值以说明 '' 中的 8 个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.