rplus.github.io
rplus.github.io copied to clipboard
[POST] selection note, 網頁文字的框選及取代
分兩種
一種是 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 左邊字元的話,就:
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
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 左側文字來示範:
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
啊~
selection 真是讓人愛不起來吶~ ( 茶~
IE? 放水流啦~ XD