1 回答

TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊
<textarea id="test"></textarea>
<script>
document.querySelector('#test').onselect = function(){
let start = this.selectionStart;
let end = this.selectionEnd;
console.log(this.value.slice(start, end));
}
</script>
selection range 是基于 DOM Tree 的。Textarea 中的內(nèi)容不由 DOM Tree管理,由 textarea 自己管理,因此你用 textarea.textContent 或者 textarea.innerText 也根本拿不到內(nèi)容。 textarea 中的內(nèi)容更改,也不會(huì)引起任何 node 或者 attribute 的變化,真正變化的是 textarea 的 value,這個(gè) value 是 textarea 的 property.
注意 isCollapsed: true
。這個(gè)值為 true 表示此時(shí)的 selection range 的長(zhǎng)度為0,只是標(biāo)記了一個(gè)位置,而不是一個(gè) range 。
好在 textarea 自己由一套 selection 接口。
添加回答
舉報(bào)