We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
分兩種 一種是 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
The text was updated successfully, but these errors were encountered:
No branches or pull requests
分兩種
一種是
div
另一種是input
&textarea
ref: https://stackoverflow.com/a/2897510
input
的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 真是讓人愛不起來吶~
( 茶~
The text was updated successfully, but these errors were encountered: