【问题标题】:How to prevent highlighting of text upon selecting text in input field如何防止在输入字段中选择文本时突出显示文本
【发布时间】:2023-04-03 00:22:01
【问题描述】:

我想复制输入字段中的文本,但不突出显示选定的文本。下面是代码sn-p,

click = () => {
    this.input_ref.current.select();
    document.execCommand('copy');
};

<input readOnly ref={this.input_ref} value="hello"/>
<button onClick={this.click}>COPY</button>

我已尝试将 css 添加到输入字段,如下所示,但没有成功。

.no_select {
-webkit-tap-highlight-color: transparent;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
outline: none;
}
<input classname="no_select" readOnly ref={this.input_ref} value="hello"/>

有人可以帮我解决这个问题吗?谢谢。

【问题讨论】:

标签: css reactjs


【解决方案1】:

我找到了我的问题的答案,并认为也会对其他人有所帮助。所以在这里发布一个答案。 在将文本复制到我使用的剪贴板后单击复制按钮 window.getSelection().removeAllRanges() 取消选择输入字段中的文本。下面是代码sn-p,

click = () => {
   this.input_ref.current.select();
   document.execCommand('copy');
   window.getSelection().removeAllRanges();
};

已编辑:以上仅适用于 chrome 而不是在 IE11 上,因此使用以下行在 chrome 和 IE11 上都可以取消选择输入字段中的文本。

document.getSelection().removeAllRanges();
document.getSelection().addRange(document.createRange());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-22
    • 2015-05-27
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 2023-04-04
    • 2010-09-21
    相关资源
    最近更新 更多