首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >点击-复制到剪贴板

点击-复制到剪贴板
EN

Stack Overflow用户
提问于 2017-08-10 14:04:32
回答 3查看 5.1K关注 0票数 5
代码语言:javascript
复制
<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();
}

当我单击该按钮时,结果将被复制,但没有粗体、下划线、行和其他格式设置。在默认情况下,如何复制它?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-08-10 14:06:41

假设您的所有样式都是内联的,则需要获取元素的html,而不是文本。类似于:

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

代码语言:javascript
复制
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");
}
票数 3
EN

Stack Overflow用户

发布于 2017-08-10 14:06:38

代码语言:javascript
复制
function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).html()).select();
  document.execCommand("copy");
  $temp.remove();
}
代码语言:javascript
复制
<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>

票数 1
EN

Stack Overflow用户

发布于 2017-08-10 14:06:32

尝试html()而不是text()

代码语言:javascript
复制
$temp.val($(element).html()).select();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45615998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档