如何将div中的文本复制到剪贴板?我有一个div,需要添加一个链接,该链接会将文本添加到剪贴板。有解决方案吗?

<p class="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>

<a class="copy-text">copy Text</a>


单击复制文本后,然后按Ctrl + V,必须将其粘贴。

评论

请参阅stackoverflow.com/questions/400212/…

Trello有一个巧妙的方法来实现此目的而无需使用Flash:stackoverflow.com/questions/17527870/…

引用此,stackoverflow.com/questions/22581345/…使用纯JavaScript获得了预期的解决方案

@MichaelScheper-一些用户甚至足够聪明,注意到我的评论以及此处的大多数答案都发布于四年前,当时基于小型Flash应用程序的zeroclipboard是唯一的跨浏览器可行选项使用剪贴板和goto解决方案。如今,所有现代浏览器都原生支持此功能,因此不再是问题,但2014年并非如此。

@adeneo:可以,但是并非所有用户都是“智能”用户,您的评论仍然有两个赞。

#1 楼

从2016年起进行编辑

从2016年起,您现在可以在大多数浏览器中将文本复制到剪贴板,因为大多数浏览器都可以使用document.execCommand("copy")来以编程方式将选择的文本复制到剪贴板。

与浏览器中的某些其他操作(例如,打开新窗口)一样,只能通过特定的用户操作(例如,单击鼠标)将内容复制到剪贴板。例如,它不能通过计时器来完成。

这是一个代码示例:




 document.getElementById("copyButton").addEventListener("click", function() {
    copyToClipboard(document.getElementById("copyTarget"));
});

function copyToClipboard(elem) {
	  // create hidden text element, if it doesn't already exist
    var targetId = "_hiddenCopyText_";
    var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
    var origSelectionStart, origSelectionEnd;
    if (isInput) {
        // can just use the original source element for the selection and copy
        target = elem;
        origSelectionStart = elem.selectionStart;
        origSelectionEnd = elem.selectionEnd;
    } else {
        // must use a temporary form element for the selection and copy
        target = document.getElementById(targetId);
        if (!target) {
            var target = document.createElement("textarea");
            target.style.position = "absolute";
            target.style.left = "-9999px";
            target.style.top = "0";
            target.id = targetId;
            document.body.appendChild(target);
        }
        target.textContent = elem.textContent;
    }
    // select the content
    var currentFocus = document.activeElement;
    target.focus();
    target.setSelectionRange(0, target.value.length);
    
    // copy the selection
    var succeed;
    try {
    	  succeed = document.execCommand("copy");
    } catch(e) {
        succeed = false;
    }
    // restore original focus
    if (currentFocus && typeof currentFocus.focus === "function") {
        currentFocus.focus();
    }
    
    if (isInput) {
        // restore prior selection
        elem.setSelectionRange(origSelectionStart, origSelectionEnd);
    } else {
        // clear temporary content
        target.textContent = "";
    }
    return succeed;
} 

 input {
  width: 400px;
} 

 <input type="text" id="copyTarget" value="Text to Copy"> <button id="copyButton">Copy</button><br><br>
<input type="text" placeholder="Click here and press Ctrl-V to see clipboard contents"> 






这里有一个更高级的演示:https://jsfiddle.net/jfriend00/v9g1x0o6/

而且,您还可以获得一个预先创建的库可使用剪贴板.js为您完成此操作。


答案的旧的历史部分

不允许通过JavaScript直接复制到剪贴板出于安全原因,由任何现代浏览器使用。最常见的解决方法是使用Flash功能将其复制到剪贴板,这只能由用户直接单击触发。

如前所述,ZeroClipboard是用于管理Flash对象的一组流行代码做副本。我用过了如果将Flash安装在浏览设备(不包括移动设备或平板电脑)上,则可以使用。


下一个最常见的解决方法是将剪贴板中的文字放入输入字段,将焦点移至该字段并建议用户按Ctrl + C复制文本。

有关此问题的其他讨论以及可能的解决方法可以在这些之前的Stack Overflow帖子中找到。 :


如何使用JavaScript复制到剪贴板?
如何使用jQuery复制文本到客户端的剪贴板?
如何在没有Flash的情况下复制到剪贴板?


这些要求使用Flash的现代替代方法的问题遭到了很多问题的否决,并且没有解决方案的答案(可能是因为不存在):


HTML5替代基于Flash的ZeroClipboard,可将数据安全复制到剪贴板吗?
不使用Flash复制到剪贴板


Internet Explorer和Firefox曾经使用非标准的API来访问剪贴板,但是它们的较新版本已经弃用了这些方法(可能出于安全原因)。


新生的标准尝试提出一种“安全”的方法来解决最常见的剪贴板问题(可能需要特定的用户操作,如Flash解决方案所要求的),并且看起来它可能已在最新版本的Firefox和Chrome中实现,但是我尚未确认。

评论


Clipboard.js刚刚添加到了此经编辑的帖子中。我在2015年8月提供了一个很好的实用程序作为对此问题的答案。

–编码员
16年1月15日在19:26

@acoder-剪贴板支持已定期更改。例如,Firefox仅在足够的情况下才最近(2015年末)启用document.execCommand(“ copy”)来依靠它来实现。因此,我正在努力使答案保持最新(最初是在大约2年前撰写的)。除了预选择文本并告诉用户手动按Ctrl + C之外,我们还没有一个可靠的Safari解决方案,但是至少在其他地方已经取得了进展。

– jfriend00
16 Jan 15 '19:30



以下是支持剪贴板API的链接:caniuse.com/#feat=clipboard

– L84
16-2-23在19:22

仅供参考,根据这组Safari发行说明,似乎Safari 10现在支持document.execCommand(“ copy”),因此此代码现在应该在Safari 10中可以使用。

– jfriend00
16年6月24日在16:25

@sebastiangodelet-公共领域。

– jfriend00
17年6月2日在4:09

#2 楼


Update 2020:此解决方案使用execCommand。尽管在编写此答案时该功能还不错,但现在认为它已过时。它仍然可以在许多浏览器上运行,但是不鼓励使用它,因为它可能会放弃对它的支持。

还有另一种非Flash方式(除了jfriend00的答案中提到的Clipboard API)。您需要选择文本,然后执行命令copy将页面上当前选中的任何文本复制到剪贴板。例如,此函数会将传递的元素的内容复制到剪贴板(建议更新)在PointZeroTwo的注释中):
function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).text()).select();
    document.execCommand("copy");
    $temp.remove();
}

它是这样工作的:

创建一个临时隐藏的文本字段。
将元素的内容复制到该文本
选择文本字段的内容。
执行命令副本,如:document.execCommand("copy")
删除临时文本字段。

注意,内部文本元素可以包含空格。因此,如果您想使用例如密码作为密码,则可以使用上面的代码中的$(element).text().trim()来修剪文本。
您可以在此处看到一个快速演示:



 function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
} 

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('#p1')">Copy P1</button>
<button onclick="copyToClipboard('#p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" /> 




主要问题是,目前并非所有浏览器都支持此功能,但您可以在以下主要浏览器中使用它:

Chrome 43
Internet Explorer 10
Firefox 41
Safari 10


更新1:这也可以通过纯JavaScript解决方案(无jQuery)实现:



 function copyToClipboard(elementId) {

  // Create a "hidden" input
  var aux = document.createElement("input");

  // Assign it the value of the specified element
  aux.setAttribute("value", document.getElementById(elementId).innerHTML);

  // Append it to the body
  document.body.appendChild(aux);

  // Highlight its content
  aux.select();

  // Copy the highlighted text
  document.execCommand("copy");

  // Remove it from the body
  document.body.removeChild(aux);

} 

 <p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('p1')">Copy P1</button>
<button onclick="copyToClipboard('p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" /> 




请注意,我们现在传递不带#号的ID。
正如madzohan在以下评论中所报告的那样,在某些情况下(本地运行文件),64位版本的Google Chrome浏览器存在一些奇怪的问题。上面的非jQuery解决方案似乎已经解决了这个问题。
Madzohan在Safari中进行了尝试,该解决方案有效,但是使用document.execCommand('SelectAll')而不是.select()(在聊天室和下面的评论中指定)。
正如PointZeroTwo在注释中指出的那样,可以对代码进行改进,使其返回成功/失败结果。您可以在此jsFiddle上看到一个演示。

更新:复制保留文本格式
正如用户在西班牙语版本的StackOverflow中指出的那样,如果您想按字面值复制元素的内容,但是如果您要复制带有格式的文本(因为复制的文本被复制到input type="text"中,格式为“丢失”),它们的效果就不好了。
一种解决方案那将是复制到内容可编辑的div中,然后以类似的方式使用execCommand复制它。这里有一个示例-单击复制按钮,然后将其粘贴到下面的内容可编辑框中:



 function copy(element_id){
  var aux = document.createElement("div");
  aux.setAttribute("contentEditable", true);
  aux.innerHTML = document.getElementById(element_id).innerHTML;
  aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)"); 
  document.body.appendChild(aux);
  aux.focus();
  document.execCommand("copy");
  document.body.removeChild(aux);
} 

 #target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
} 

 <p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('demo')">Copy Keeping Format</button> 

<div id="target" contentEditable="true"></div> 




在jQuery中,就像这样:



 function copy(selector){
  var $temp = $("<div>");
  $("body").append($temp);
  $temp.attr("contenteditable", true)
       .html($(selector).html()).select()
       .on("focus", function() { document.execCommand('selectAll',false,null); })
       .focus();
  document.execCommand("copy");
  $temp.remove();
} 

 #target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
} 

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('#demo')">Copy Keeping Format</button> 

<div id="target" contentEditable="true"></div> 




评论


奇怪...在这里工作,但我无法在本地工作0o jquery-1.11.3 Chrome 43.0.2357.130(64位)

– Madzohan
2015年6月25日15:01



@madzohan好的,我能够重现该问题。这很奇怪,因为我只能在64位Chrome的本地(file://)上重现它。我还找到了一个适用于我的快速解决方案:使用纯JavaScript而不是jQuery。我将用该代码更新答案。请检查它,让我知道它是否适合您。

–阿尔瓦罗·蒙托罗(Alvaro Montoro)
15年6月25日在16:30

FWIW-document.execCommand(“ copy”)返回一个布尔值(IE,Chrome,Safari),指示复制是否成功。它可用于在失败时显示错误消息。 Firefox在失败时引发异常(至少在v39中),需要try / catch来处理错误。

– PointZeroTwo
15年7月27日在17:41

在添加以下几行以确保aux在页面上可见之前,这对我不起作用:aux.style.position =“ fixed”; aux.style.top = 0;在appendChild调用之上。

–ariscris
2015年10月7日18:15



原始的jQuery实现无法保留换行符,因为它使用了INPUT元素。使用TEXTAREA可以解决此问题。

– thomasfuchs
17年10月10日在14:20

#3 楼

剪贴板.js是一个很好的实用程序,它允许在不使用Flash的情况下将文本或HTML数据复制到剪贴板。它很容易使用;只需包含.js并使用类似这样的内容:

<button id='markup-copy'>Copy Button</button>

<script>
    document.getElementById('markup-copy').addEventListener('click', function() {
        clipboard.copy({
            'text/plain': 'Markup text. Paste me into a rich text editor.',
            'text/html': '<i>here</i> is some <b>rich text</b>'
        }).then(
            function(){console.log('success'); },
            function(err){console.log('failure', err);
        });
    });
</script>


clipboard.js也位于GitHub上。

编辑于2016年1月15日:顶部答案今天进行了编辑,以引用我在2015年8月发布的答案中的相同API。先前的文本是指示用户使用ZeroClipboard。只是想清楚一点,我并没有从jfriend00的答案中得出这个结论,反之亦然。

评论


剪贴板js-已过时作者消息:请迁移到github.com/lgarron/clipboard-polyfill

–叶夫根尼·阿凡纳西耶夫(Yevgeniy Afanasyev)
18年6月25日在2:54

#4 楼

简单是最终的复杂性。
如果您不希望看到要复制的文本:
jQuery:

$('button.copyButton').click(function(){
    $(this).siblings('input.linkToCopy').select();      
    document.execCommand("copy");
});


HTML:

<button class="copyButton">click here to copy</button>
<input class="linkToCopy" value="TEXT TO COPY"
style="position: absolute; z-index: -999; opacity: 0;" />


评论


在ipad上似乎无法使用,尚未测试,但建议的解决方案在这里:stackoverflow.com/a/34046084

–user1063287
18-09-27在14:16

这对我有用,但是如果要复制的文本包含回车符,那么您也可以改用textarea。

– Alex
6月6日15:33

#5 楼

有换行符(阿尔瓦罗·蒙托罗的回答延伸)

var ClipboardHelper = {

    copyElement: function ($element)
    {
       this.copyText($element.text())
    },
    copyText:function(text) // Linebreaks with \n
    {
        var $tempInput =  $("<textarea>");
        $("body").append($tempInput);
        $tempInput.val(text).select();
        document.execCommand("copy");
        $tempInput.remove();
    }
};

ClipboardHelper.copyText('Hello\nWorld');
ClipboardHelper.copyElement($('body h1').first());


#6 楼

没有Flash或其他任何要求的更好方法是剪贴板。您需要做的就是在任何按钮上添加data-clipboard-target="#toCopyElement",对其进行初始化,然后它将ID为new Clipboard('.btn');的DOM内容复制到剪贴板。这是一个通过链接复制问题中提供的文本的代码段。

虽然有一个限制,但它不能在safari中使用,但可以在所有其他浏览器(包括移动浏览器)上使用,因为它不能使用Flash




 toCopyElement 

 $(function(){
  new Clipboard('.copy-text');
}); 




#7 楼

<div class="form-group">
    <label class="font-normal MyText">MyText to copy</label>&nbsp;
    <button type="button" class="btn btn-default btn-xs btnCopy" data="MyText">Copy</button>
</div>


$(".btnCopy").click(function () {
        var element = $(this).attr("data");
        copyToClipboard($('.' + element));
  });

function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).text()).select();
    document.execCommand("copy");
    $temp.remove();
}


评论


不错的解决方法。也许将.addClass(“ hidden”)添加到标记中,使其永远不会在浏览器中显示?

–罗兰
18年1月31日在11:01

#8 楼

jQuery简单解决方案。

应该由用户的点击触发。

$("<textarea/>").appendTo("body").val(text).select().each(function () {
            document.execCommand('copy');
        }).remove();


#9 楼

您可以通过单击按钮在剪贴板中的页面中将此代码用于复制输入值

这是HTML

<input type="text" value="xxx" id="link" class="span12" />
<button type="button" class="btn btn-info btn-sm" onclick="copyToClipboard('#link')">
    Copy Input Value
</button>


然后为此html,我们必须使用此JQuery代码

function copyToClipboard(element) {
    $(element).select();
    document.execCommand("copy");
}


这是此问题的最简单解决方案

#10 楼

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link href="css/index.css" rel="stylesheet" />
    <script src="js/jquery-2.1.4.min.js"></script>
    <script>
        function copy()
        {
            try
            {
                $('#txt').select();
                document.execCommand('copy');
            }
            catch(e)
            {
                alert(e);
            }
        }
    </script>
</head>
<body>
    <h4 align="center">Copy your code</h4>
    <textarea id="txt" style="width:100%;height:300px;"></textarea>
    <br /><br /><br />
    <div align="center"><span class="btn-md" onclick="copy();">copy</span></div>
</body>
</html>


评论


这只能用于Textarea和文本框。

– Vignesh Chinnaiyan
16年6月17日在10:01

#11 楼

输入字段没有display: none非常重要。浏览器不会选择文本,因此不会被复制。使用宽度为0px的opacity: 0来解决此问题。

#12 楼

复制内容是最简单的方法

 <div id="content"> Lorepm ispum </div>
 <button class="copy" title="content">Copy Sorce</button>

function SelectContent(element) {
                        var doc = document
                            , text = doc.getElementById(element)
                            , range, selection
                        ;    
                        if (doc.body.createTextRange) {
                            range = document.body.createTextRange();
                            range.moveToElementText(text);
                            range.select();
                        } else if (window.getSelection) {
                            selection = window.getSelection();        
                            range = document.createRange();
                            range.selectNodeContents(text);
                            selection.removeAllRanges();
                            selection.addRange(range);

                        }
                         document.execCommand('Copy');
                    }
                    $(".copy").click(function(){

                         SelectContent( $(this).attr('title'));
                    });


#13 楼

大部分建议的答案都会创建一个额外的临时隐藏输入元素。因为当今大多数浏览器都支持div内容编辑,所以我提出了一种不创建隐藏元素,保留文本格式并使用纯JavaScript或jQuery库的解决方案。

这是一个极简的框架实现,它使用了我可能想到的最少的代码行:




 //Pure javascript implementation:
document.getElementById("copyUsingPureJS").addEventListener("click", function() {
  copyUsingPureJS(document.getElementById("copyTarget"));
  alert("Text Copied to Clipboard Using Pure Javascript");
});

function copyUsingPureJS(element_id) {
  element_id.setAttribute("contentEditable", true);
  element_id.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
  element_id.focus();
  document.execCommand("copy");
  element_id.removeAttribute("contentEditable");
  
}

//Jquery:
$(document).ready(function() {
  $("#copyUsingJquery").click(function() {
    copyUsingJquery("#copyTarget");
  });
 

  function copyUsingJquery(element_id) {
    $(element_id).attr("contenteditable", true)
      .select()
      .on("focus", function() {
        document.execCommand('selectAll', false, null)
      })
      .focus()
    document.execCommand("Copy");
    $(element_id).removeAttr("contenteditable");
     alert("Text Copied to Clipboard Using jQuery");
  }
}); 

 #copyTarget {
  width: 400px;
  height: 400px;
  border: 1px groove gray;
  color: navy;
  text-align: center;
  box-shadow: 0 4px 8px 0 gray;
}

#copyTarget h1 {
  color: blue;
}

#copyTarget h2 {
  color: red;
}

#copyTarget h3 {
  color: green;
}

#copyTarget h4 {
  color: cyan;
}

#copyTarget h5 {
  color: brown;
}

#copyTarget h6 {
  color: teal;
}

#pasteTarget {
  width: 400px;
  height: 400px;
  border: 1px inset skyblue;
} 

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="copyTarget">
  <h1>Heading 1</h1>
  <h2>Heading 2</h2>
  <h3>Heading 3</h3>
  <h4>Heading 4</h4>
  <h5>Heading 5</h5>
  <h6>Heading 6</h6>
  <strong>Preserve <em>formatting</em></strong>
  <br/>
</div>

<button id="copyUsingPureJS">Copy Using Pure JavaScript</button>
<button id="copyUsingJquery">Copy Using jQuery</button>
<br><br> Paste Here to See Result
<div id="pasteTarget" contenteditable="true"></div> 




#14 楼

要复制的文本在文本输入中,例如:<input type="text" id="copyText" name="copyText">,然后在按钮上单击上方的文本应将其复制到剪贴板,因此按钮如下:<button type="submit" id="copy_button" data-clipboard-target='copyText'>Copy</button>您的脚本应类似于:

<script language="JavaScript">
$(document).ready(function() {
var clip = new ZeroClipboard($("#copy_button"), {
  moviePath: "ZeroClipboard.swf"
}); 
});

</script>


对于CDN文件



(zeroclipboard.swf):

(zeroclipboard.js):

注意:ZeroClipboard.swfZeroClipboard.js“文件应与使用此功能的文件位于同一文件夹中,否则,您必须像在页面上添加<script src=""></script>一样添加。

评论


Flash正在走Geocities的道路。

–编码员
2015年9月12日于12:26

#15 楼

您只需使用此lib即可轻松实现复制目标!

https://clipboardjs.com/


不应将文本复制到剪贴板硬。
不需要数十个步骤来配置或加载数百KB。但是大多数
,它不应该依赖于Flash或任何过分膨胀的框架。

这就是剪贴板.js存在的原因。



https://github.com/zeroclipboard/zeroclipboard

http://zeroclipboard.org/


ZeroClipboard库提供了使用不可见的Adobe Flash电影和JavaScript
接口将文本复制到
剪贴板的简便方法。


#16 楼

Clipboard-polyfill库是用于现代基于Promise的异步剪贴板API的polyfill。

在CLI中安装:

npm install clipboard-polyfill 


作为剪贴板导入JS文件

window.clipboard = require('clipboard-polyfill');


示例

我正在与require("babel-polyfill");捆绑使用它,并在chrome 67上进行了测试。所有这些都非常适合生产。

#17 楼

从2020年开始,您应该使用剪贴板Api。
navigator.clipboard.writeText('text here you want to copy').then(function () {
    alert('It worked! Do a CTRL - V to paste')
}, function () {
    alert('Failure to copy. Check permissions for clipboard')
});

这里是有关与剪贴板交互的更多信息

#18 楼

html代码在这里

    <input id="result" style="width:300px"/>some example text
    <button onclick="copyToClipboard('result')">Copy P1</button>
    <input type="text" style="width:400px" placeholder="Paste here for test" />


JS代码:

     function copyToClipboard(elementId) {

                      // Create a "hidden" input
                      var aux = document.createElement("input");

                      aux.setAttribute("value", document.getElementById(elementId).value);
                      // Append it to the body
                      document.body.appendChild(aux);
                      // Highlight its content
                      aux.select();
                      // Copy the highlighted text
                      document.execCommand("copy");
                      // Remove it from the body
                      document.body.removeChild(aux);
                    }


评论


更改:将.value更改为.innerHTML

–奥马尔·N·沙马里(Omar N Shamali)
19年4月29日在16:34



#19 楼

您可以复制HTML元素文本之外的单个文本。

        var copyToClipboard = function (text) {
            var $txt = $('<textarea />');

            $txt.val(text)
                .css({ width: "1px", height: "1px" })
                .appendTo('body');

            $txt.select();

            if (document.execCommand('copy')) {
                $txt.remove();
            }
        };


#20 楼

纯JS,没有内联onclick,用于成对的类“内容-复制按钮”。如果元素很多,会更舒适)




 (function(){

/* Creating textarea only once, but not each time */
let area = document.createElement('textarea');
document.body.appendChild( area );
area.style.display = "none";

let content = document.querySelectorAll('.js-content');
let copy    = document.querySelectorAll('.js-copy');

for( let i = 0; i < copy.length; i++ ){
  copy[i].addEventListener('click', function(){
    area.style.display = "block";
    /* because the classes are paired, we can use the [i] index from the clicked button,
    to get the required text block */
    area.value = content[i].innerText;
    area.select();
    document.execCommand('copy');   
    area.style.display = "none";

    /* decorative part */
    this.innerHTML = 'Cop<span style="color: red;">ied</span>';
    /* arrow function doesn't modify 'this', here it's still the clicked button */
    setTimeout( () => this.innerHTML = "Copy", 2000 );
  });
}

})(); 

 hr { margin: 15px 0; border: none; } 

 <span class="js-content">1111</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">2222</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">3333</span>
<button class="js-copy">Copy</button> 





较旧的浏览器支持:




 (function(){

var area = document.createElement('textarea');
document.body.appendChild( area );
area.style.display = "none";

var content = document.querySelectorAll('.js-content');
var copy    = document.querySelectorAll('.js-copy');

for( var i = 0; i < copy.length; i++ ){
  copyOnClick(i);
}

function copyOnClick(i){
  copy[i].addEventListener('click', function(){
    area.style.display = "block";
    area.value = content[i].innerText;
    area.select();
    document.execCommand('copy');   
    area.style.display = "none";
    
    var t = this;
    t.innerHTML = 'Cop<span style="color: red;">ied</span>';
    setTimeout( function(){
      t.innerHTML = "Copy"
    }, 2000 );
  });
}

})(); 

 hr { margin: 15px 0; border: none; } 

 <span class="js-content">1111</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">2222</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">3333</span>
<button class="js-copy">Copy</button> 




#21 楼

两者都将像魅力一样工作:),

JAVASCRIPT:

function CopyToClipboard(containerid) {
if (document.selection) { 
    var range = document.body.createTextRange();
    range.moveToElementText(document.getElementById(containerid));
    range.select().createTextRange();
    document.execCommand("copy"); 

} else if (window.getSelection) {
    var range = document.createRange();
     range.selectNode(document.getElementById(containerid));
     window.getSelection().addRange(range);
     document.execCommand("copy");
     alert("text copied") 
}}


也在html中,

<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>

<div id="div1" >Text To Copy </div>

<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>


JQUERY:
https://paulund.co.uk/jquery-copy-clipboard