2017-08-10 65 views
5
<p id="p1"> 
...here is a lot of text (html) mixed with php... 
</p> 
<button onclick="copyToClipboard('#p1')">Copy to clipboard</button> 
------ 
JS 

function copyToClipboard(element) { 
    var $temp = $("<input>"); 
    $("body").append($temp); 
    $temp.val($(element).text()).select(); 
    document.execCommand("copy"); 
    $temp.remove(); 
} 

當我按一下按鈕,結果被複制,但沒有粗體,下劃線,行和其他格式的東西。 如何複製它,因爲它默認顯示?在點擊 - 複製到剪貼板

+0

我認爲這將有所幫助,如果你描述它將被粘貼。如果你抓取所有的html,它可能不會按照你的要求粘貼。 – Brian

+0

要gmail正文消息。我只是希望「點擊複製」複製與我用鼠標選擇文本時的複製相同,並複製它。 – FabianCannes

+0

我可以看到如何有用。好問題。 +1。 – Brian

回答

2

假設你所有的風格是內聯,您需要獲得元素,而不是文本的HTML。喜歡的東西:

function copyToClipboard(element) { 
    var $temp = $("<input>"); 
    $("body").append($temp); 
    $temp.val($(element).html()).select(); //Note the use of html() rather than text() 
    document.execCommand("copy"); 
    $temp.remove(); 
} 

編輯基於評論:

複製格式到像一個Gmail郵件正文或者你有實際選擇的元素作爲一個範圍內的Word文檔。將html內容插入到textarea中時,實際上是在複製原始文本。你想做這樣的事情:

function copyToClipboard(element) { //Note, element should be a node rather than a jQuery instance. 
    var selection = window.getSelection(), //Get the window selection 
     selectData = document.createRange(); //Create a range 

     selection.removeAllRanges(); //Clear any currently selected text. 
     selectData.selectNodeContents(element); //Add the desired element to the range you want to select. 
     selection.addRange(selectData); //Highlight the element (this is the same as dragging your cursor over an element) 
     var copyResult = document.execCommand("copy"); //Execute the copy. 

     if(copyResult) //was the copy successful? 
      selection.removeAllRanges(); //Clear the highlight. 
     else 
      alert("Your browser does not support clipboard commands, press ctrl+c"); 
} 
+0

使用此方法,所有html源代碼都被複制,它不會顯示格式。 – FabianCannes

+0

你想把它粘貼到哪裏? – GentlemanMax

+0

給Gmail郵件正文。 – FabianCannes

0

嘗試HTML(),而不是文本()

$temp.val($(element).html()).select(); 
+0

心靈解釋多一點? –

1

function copyToClipboard(element) { 
 
    var $temp = $("<input>"); 
 
    $("body").append($temp); 
 
    $temp.val($(element).html()).select(); 
 
    document.execCommand("copy"); 
 
    $temp.remove(); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p id="p1"> 
 
...here is a lot of <b>text</b> (html) mixed with php... 
 
</p> 
 
<button onclick="copyToClipboard('#p1')">Copy to clipboard</button>