在焦点输入时保持选择文本 [英] Keep text selected when focus input
问题描述
这个问题已经被问到,但是到目前为止还没有工作答案,所以我很想再次打开它,希望我们能找到它。
This question has already been asked but until now there is no working answer so I am tempting to open it again hopefully we can find a hack to it.
I有一个contentEditable段落和一个文本输入,当我选择一些文本并点击输入时,选择就消失了。
I have a contentEditable paragraph and a text input, when I select some text and click the input, the selection is gone.
所以我试图保存选择输入mousedown 并将其恢复到mouseup ,是的它可以正常工作(正如在firefox中预期的那样)但是......在Chrome中输入失去焦点 :(
So I've tried to save the selection on input mousedown and to restore it back on mouseup and yeah it works ( as expected in firefox) But... in chrome the input lose focus :(
查看它的实际效果(使用chrome ): https://jsfiddle.net/mody5/noygdhdu/
See it in action (use chrome) : https://jsfiddle.net/mody5/noygdhdu/
这是我用过的代码:
HTML
<p contenteditable="true">
Select something up here and click the input below
<br> on firefox the input get the focus and the text still selected.
<br> on chrome the text still selected but the input lose focus
</p>
<input type="text" id="special" style="border: solid blue 1px">
javascript
javascript
function saveSelection() {
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
return sel.getRangeAt(0);
}
} else if (document.selection && document.selection.createRange) {
return document.selection.createRange();
}
return null;
}
function restoreSelection(range) {
if (range) {
if (window.getSelection) {
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.selection && range.select) {
range.select();
}
}
}
var specialDiv = document.getElementById("special");
var savedSel = null;
specialDiv.onmousedown = function() {
savedSel = saveSelection(); // save the selection
};
specialDiv.onmouseup = function() {
restoreSelection(savedSel); // restore the selection
};
推荐答案
因为我无法对maioman发表评论(一些声望需要:)),这里有一点点他的aswer:
As I can't comment on maioman (some reputation needed :)), here a little addition to his aswer:
它在firefox中不起作用的原因是将焦点放在输入字段上会删除选择。
The reason it doesn't work in firefox is that putting the focus on the input field removes the selection.
如果你在p上放一个mouseup事件而不是输入字段上的焦点事件,一切正常:
It all works fine if you put a mouseup event on the p instead of a focus event on the inputfield:
p.addEventListener('mouseup', () => {
highlight(select()); // save the selection
})
这篇关于在焦点输入时保持选择文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!