[英]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.