【问题标题】:Firefox not allowing selection on two text input at same timeFirefox 不允许同时选择两个文本输入
【发布时间】:2019-07-29 00:43:33
【问题描述】:

我在 HTML 页面中有两个基本的文本输入,如果它们都不是焦点并且我按 CTR+A 或 CMD+A 快捷方式,那么在 Firefox 上没有选择两个文本输入的内容,在 chrome 上工作正常

<div>
<input type="text" onkeydown="myFunction(event)" value="test">
<input type="text" value="test1">
</div> 

即使选择 API 在 Firefox 上也没有像预期的那样工作,即它没有同时选择两个文本框。 我创建了this fiddle 来解释问题。我需要选择特定父节点(在我的情况下为 div)下的所有文本输入内容,这个小提琴在 chrome 和 safari 上都可以正常工作,但在 firefox 上却没有,

我已经尝试了范围 API 和选择 API 如下

window.getSelection().selectAllChildren(event.target.parentNode);

let range = document.createRange();

range.setStart(event.target.parentNode, 0);
range.setEnd(event.target.parentNode, 1);

window.getSelection().removeAllRanges();
window.getSelection().addRange(range);

【问题讨论】:

    标签: javascript html firefox textselection


    【解决方案1】:

    是的,Firefox 不允许选择输入内容。我猜这是一种安全措施。

    您可以通过设置输入的 textContent 属性来解决该问题,这样即使在 Firefox 中您也可以选择和复制其内容。

    我在selectionchange 事件中执行此操作,但您可以在最适合您的情况下随时调用它。

    document.onselectionchange = e => {
      console.log(e);
      // every time the selection changes
      document.querySelectorAll('input').forEach(el => {
        // except when we are the one in focus
        if(document.activeElement === el) return;
        // update each <input>'s textContent property
        el.textContent = el.value;
      })
    }
    <p>Try to select all (ctrl+A) the page and copy to clipboard (ctrl+C)</p>
    
    <div>
      <input type="text" value="test">
      <input type="text" value="test1">
    </div>

    【讨论】:

    • 感谢您的快速回复,我已经测试了您的解决方案,如果我们需要默认全选和复制行为,它可以正常工作,但是您的解决方案不会强制 Firefox 在文本输入字段中选择文本,这与 chrome 和safari,即使使用 Selection API,firefox 的行为方式也类似,即它在模型的某个地方进行场景后面的选择,我可以通过选择 API 访问该选择。使用您的解决方案,我不需要单独处理全部选择,但即使该副本在 safari 上无法顺利运行,我将自己处理所有事件,会及时通知您。再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多