假设你所有的风格是内联,您需要获得元素,而不是文本的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