構建如下所示的編輯器——我需要用戶能夠選擇一些文本,然后使用輸入來做某事而不會丟失選擇。
function doReplace(){
const s = document.getSelection()
if(s?.anchorNode.parentElement.id != "out")return;
console.log('replace')
out.innerText = out.innerText.substring(0,s.anchorOffset) (inp.value||'FALLBACK') out.innerText.substring(s.extentOffset)
}
<input id="inp" placeholder="replace selection to" >
<button onclick="doReplace()">replace</button>
<p id="out">select some here and replace</p>
這個演示重現了這個問題:一個人不能在不丟失文本選擇的情況下使用輸入。
如何在不改變焦點的情況下輸入?
真實世界的用例類似于為選擇設定字體大小。

編輯
也許快取選擇是要走的路,但會失去視覺指示,嘗試恢復選擇會再次失去焦點。
let s
function doReplace() {
if (s?.anchorNode?.parentElement.id != "out") return;
console.log('replace')
out.innerText = out.innerText.substring(0, s.anchorOffset) (inp.value || 'FALLBACK') out.innerText.substring(s.extentOffset)
}
function doRestore() {
if (s?.anchorNode?.parentElement.id != "out") return;
const sel = document.getSelection();
sel.setBaseAndExtent(s.anchorNode, s.anchorOffset, s.anchorNode, s.extentOffset);
}
out.addEventListener('mouseup', () => {
const sel = document.getSelection()
if(!sel)return;
const {
anchorNode,
anchorOffset,
extentOffset
} = sel || {}
s = {
text: sel.toString(),
anchorNode,
anchorOffset,
extentOffset
}
console.log(`sel`, s.anchorOffset, s.extentOffset, s.text)
}, false);
<input id="inp" placeholder="replace selection to" autocomplete="false" onfocus="doRestore()">
<button onclick="doReplace()">replace</button>
<p id="out">select some here and replace</p>
uj5u.com熱心網友回復:
如果我錯了,請糾正我,但我認為這不可能。input/textarea 標簽需要焦點,以便用戶能夠輸入。
我建議您使用 EventListener 而不是輸入標簽:
function doReplace(){
const s = document.getSelection()
if(s?.anchorNode.parentElement.id != "out")return;
console.log('replace')
out.innerText = out.innerText.substring(0,s.anchorOffset) (inp.value||'FALLBACK') out.innerText.substring(s.extentOffset)
}
window.addEventListener("keydown", event => {
document.getElementById("field").innerHTML = event.key
});
<div id="field"></div>
<button onclick="doReplace()">replace</button>
<p id="out">select some here and replace</p>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/477162.html
標籤:javascript html dom 输入
