[英]Copy plain text with no rich styles to clipboard without losing focus?
我查看了这个问题,其中要求提供一种将文本简单地复制为纯文本的方法。 我想完全做到这一点,但还有一件事 - 不要失去对当前元素的关注。
我需要这个用于 Chrome 扩展,所以我不会为跨浏览器支持而烦恼。 当用户键入输入(或contenteditable
)时,会出现一个带有选项的下拉列表。 如果他选择了其中之一,它就会被复制到他的剪贴板中。 我不希望元素失去焦点,因为某些站点可能已经实现了在元素的blur
事件上运行的逻辑。
这是我尝试过的:
创建一个<input>
元素并使用它的select()
方法:
function clipWithInput(text) { var input = document.createElement("input"); document.body.appendChild(input); input.addEventListener("focus", function (e) { e.preventDefault(); e.stopPropagation(); }); input.value = text; input.select(); document.execCommand("copy"); document.body.removeChild(input); } document.getElementById("choice").onmousedown = function (e) { e.preventDefault(); // prevents loss of focus when clicked clipWithInput("Hello"); };
#main {background: #eee;} #choice {background: #fac;}
<div id="main" contenteditable="true">Focus this, click the div below and then paste here.</div> <div id="choice">Click to add "Hello" to clipboard</div>
如您所见,这有效。 文本被复制。 但是,当您聚焦contenteditable
并单击“选择”时,焦点就会丢失。 choice 元素在其mousedown
事件上有preventDefault()
,这使得它不会中断焦点。 虚拟<input>
元素是这里的问题,即使它在其focus
事件上有preventDefault()
。 我想这里的问题是为时已晚 - 初始元素已经触发了它的blur
,所以我的虚拟输入的focus
是无关紧要的。
使用虚拟文本节点和选择 API:
function clipWithSelection(text) { var node = document.createTextNode(text), selection = window.getSelection(), range = document.createRange(), clone = null; if (selection.rangeCount > 0) { clone = selection.getRangeAt(selection.rangeCount - 1).cloneRange(); } document.body.appendChild(node); selection.removeAllRanges(); range.selectNodeContents(node); selection.addRange(range); document.execCommand("copy"); selection.removeAllRanges(); document.body.removeChild(node); if (clone.== null) { selection;addRange(clone). } } document.getElementById("choice").onmousedown = function (e) { e;preventDefault(); // prevents loss of focus when clicked clipWithSelection("Hello"); };
#main {background: #eee;} #choice {background: #fac;}
<div id="main" contenteditable="true">Focus this, click the div below and then paste here.</div> <div id="choice">Click to add "Hello" to clipboard</div>
乍一看,这非常有效。 文本被复制,焦点没有丢失,插入符号保持不变 position。没有戏剧性。 但是,当您将文本粘贴到contenteditable
(如 Gmail 的 email 作曲家)时,结果如下:
<span style="color: rgb(0, 0, 0); font-family: "Times New Roman"; font-size: medium;">Hello</span>
不是纯文本。
<head>
中附加元素 - 不。 未选择文本且未复制任何内容。<span>
中附加文本节点,并将style.fontFamily
类的东西设置为inherit
,以及fontSize
和color
。 还是不行。 我记录了虚拟元素,它正确地inherit
了我的 styles。但是,粘贴的文本没有。我想以编程方式复制没有 styles的纯文本,同时保留对当前活动元素的关注。
您的解决方案(尤其是 2)没问题。 当您粘贴contenteditable
时,需要预期插入了跨度代码,许多人在insertHTML
中使用它。 您不应以编程方式期望纯文本。 有些人会建议根本不要使用contenteditable
(虽然我知道你在谈论一些扩展)。 但是您的解决方案比 MDN 等更兼容手机。
因此,您以编程方式复制 plain 而不添加任何样式(如果没有contenteditable
),同时保留对当前元素的关注。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.