Open Rplus opened 7 years ago
分兩種 一種是 div 另一種是 input & textarea ref: https://stackoverflow.com/a/2897510
div
input
textarea
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
input.selectionStart 是 caret 的位置 若是一般的 caret 位移(非選取模式),則該值會與 input.selectionEnd 相同 所以若是要取代 caret 左邊字元的話,就:
input.selectionStart
input.selectionEnd
let index = input.selectionStart; let txt = input.value; input.value = txt.substr(0, index - 1) + _char + txt.substr(index - 1 + _char.length); // update string input.setSelectionRange(index, index); // 重新定位 caret
https://developer.mozilla.org/en-US/docs/Web/API/Selection
div 包括加了 contenteditable 的東西 它要用 document.getSelection() 來抓出目前 caret 的資料: node, offset… 可以看 MDN 裡有寫一堆 property: anchorNode, anchorOffset, focusNode, focusOffset, isCollapsed, rangeCount, type 一樣拿取代 caret 左側文字來示範:
contenteditable
document.getSelection()
node
offset
anchorNode
anchorOffset
focusNode
focusOffset
isCollapsed
rangeCount
type
let selection = window.getSelection(); let selectNode = selection.anchorNode; let index = selection.anchorOffset - 1; let _str = selectNode.data; selectNode.textContent = _str.substr(0, index) + _char + _str.substr(index + _char.length); // update string selection.collapse(selectNode, index + 1); // 重新定位 caret
有時要小心 selectNode.data 沒東西 遇到這樣的狀況就要改用 selectNode.textContent 來做 fallback
selectNode.data
selectNode.textContent
啊~ selection 真是讓人愛不起來吶~ ( 茶~
( 茶~
IE? 放水流啦~ XD
分兩種 一種是
div
另一種是input
&textarea
ref: https://stackoverflow.com/a/2897510input
的https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
input.selectionStart
是 caret 的位置 若是一般的 caret 位移(非選取模式),則該值會與input.selectionEnd
相同 所以若是要取代 caret 左邊字元的話,就:div
的https://developer.mozilla.org/en-US/docs/Web/API/Selection
div 包括加了
contenteditable
的東西 它要用document.getSelection()
來抓出目前 caret 的資料:node
,offset
… 可以看 MDN 裡有寫一堆 property:anchorNode
,anchorOffset
,focusNode
,focusOffset
,isCollapsed
,rangeCount
,type
一樣拿取代 caret 左側文字來示範:有時要小心
selectNode.data
沒東西 遇到這樣的狀況就要改用selectNode.textContent
來做 fallback啊~ selection 真是讓人愛不起來吶~
( 茶~