Skip to content
New issue

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

[POST] selection note, 網頁文字的框選及取代 #40

Open
Rplus opened this issue Jun 29, 2017 · 0 comments
Open

[POST] selection note, 網頁文字的框選及取代 #40

Rplus opened this issue Jun 29, 2017 · 0 comments

Comments

@Rplus
Copy link
Owner

Rplus commented Jun 29, 2017

分兩種
一種是 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant