假設你所有的風格是內聯,您需要獲得元素,而不是文本的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");
}
我認爲這將有所幫助,如果你描述它將被粘貼。如果你抓取所有的html,它可能不會按照你的要求粘貼。 – Brian
要gmail正文消息。我只是希望「點擊複製」複製與我用鼠標選擇文本時的複製相同,並複製它。 – FabianCannes
我可以看到如何有用。好問題。 +1。 – Brian