jquery - 单击 - 复制到剪贴板

标签 jquery html

<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 内容插入文本区域时,您实际上是在复制原始文本。你想做这样的事情:

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

关于jquery - 单击 - 复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45615998/

相关文章:

javascript - 将 jQuery document.ready() 包含为包含文件

javascript - 使用 javascript/jquery 检查 .css 样式表的名称

Jquery onclick 事件改变 Font Awesome 图标

javascript - 在 JavaScript 代码中传递新参数以定位 HTML 属性

javascript - jQuery each 和附加点击事件

javascript - jQuery 延迟 promise 似乎不适用于打开新窗口

jquery - 当用户到达屏幕底部时淡出元素

javascript - html中的隐藏文本框

php - 相同的 CSS 文件首先在开头加载多次,然后在结尾加载?

html - 为什么当我悬停在任何东西上时元素会移动(仅适用于 IE6)