在点击 - 复制到剪贴板
问题描述:
<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();
}
当我按一下按钮,结果被复制,但没有粗体,下划线,行和其他格式的东西。 如何复制它,因为它默认显示?在点击 - 复制到剪贴板
答
假设你所有的风格是内联,您需要获得元素,而不是文本的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(),而不是文本()
$temp.val($(element).html()).select();
+0
心灵解释多一点? –
答
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>
我认为这将有所帮助,如果你描述它将被粘贴。如果你抓取所有的html,它可能不会按照你的要求粘贴。 – Brian
要gmail正文消息。我只是希望“点击复制”复制与我用鼠标选择文本时的复制相同,并复制它。 – F*Cannes
我可以看到如何有用。好问题。 +1。 – Brian