繁体   English   中英

点击 - 复制到剪贴板

[英]On click - copy to clipboard

<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");
}

 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()而不是text()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM