如何将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,它必须被粘贴。


编辑截止2016年

截至2016年,您现在可以在大多数浏览器中将文本复制到剪贴板,因为大多数浏览器都能够使用document.execCommand(“复制”)以编程方式将所选文本复制到剪贴板。

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

下面是一个代码示例:

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/

你也可以用clipboard.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中部分实现,但我还没有证实这一点。


文本复制是在文本输入,如:< input type="text" id="copyText" name="copyText">和,在按钮点击上面的文本应该被复制到剪贴板,所以按钮是像:<button type="submit" id="copy_button" data-clipboard-target='copyText'>复制</button>你的脚本应该像:

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

</script>

CDN文件

(zeroclipboard.swf): (zeroclipboard.js):

注意:ZeroClipboard.swf和ZeroClipboard.js”文件应该和你使用这个功能的文件在同一个文件夹中,或者你必须包括像我们包括<script src=""></script>在我们的页面上。


更新2020:此解决方案使用execCommand。虽然这个功能在写这篇文章的时候还不错,但现在被认为已经过时了。它仍然可以在许多浏览器上工作,但不鼓励使用它,因为支持可能会被放弃。

还有另一种非flash的方式(除了jfriend00的回答中提到的剪贴板API)。您需要选择文本,然后执行复制命令,将当前页面上选择的任何文本复制到剪贴板。

例如,这个函数将把传递的元素的内容复制到剪贴板中(在PointZeroTwo的注释中更新了建议):

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

它是这样工作的:

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

注意元素的内部文本可以包含空格。因此,如果你想使用if作为密码,你可以在上面的代码中使用$(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" />

注意,我们传递的是没有# now的id。

正如madzohan在下面的评论中报告的那样,在某些情况下,64位版本的谷歌Chrome浏览器存在一些奇怪的问题(在本地运行文件)。使用上面的非jquery解决方案似乎可以解决这个问题。

Madzohan尝试在Safari中,解决方案工作,但使用document.execCommand('SelectAll')而不是使用.select()(在聊天和下面的评论中指定)。

正如PointZeroTwo在评论中指出的那样,可以对代码进行改进,使其返回成功/失败结果。您可以在这个jsFiddle上看到一个演示。


更新:副本保持文本格式

正如一个用户在StackOverflow的西班牙版本中指出的那样,如果你想字面上复制一个元素的内容,上面列出的解决方案非常有效,但是如果你想用格式粘贴复制的文本,它们就不那么有效了(因为它被复制到输入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>


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的答案中抽取这个,而是相反。


这是复制内容的最简单方法

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

<!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>

这里是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);
                    }

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

虽然有一个限制是它不能在safari上运行,但它可以在所有其他浏览器上运行,包括移动浏览器,因为它不使用flash

$(函数(){ 新剪贴板(“.copy-text”); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> < script src = " https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js " > < /脚本> <p id="content">Lorem Ipsum只是印刷排版行业的假文本。自16世纪以来,Lorem Ipsum一直是行业标准的虚拟文本 <a class="copy- Text " data-clipboard-target="#content" href="#">copy Text</a>


你可以使用这个库轻松实现复制目标!

https://clipboardjs.com/

将文本复制到剪贴板应该不难。它不需要 数十个配置步骤或数百kb的加载。但是大部分 总之,它不应该依赖于Flash或任何膨胀的框架。 这就是clipboard.js存在的原因。

or

https://github.com/zeroclipboard/zeroclipboard

http://zeroclipboard.org/

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


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

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());

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

jQuery简单解决方案。

应由用户点击触发。

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

2022年6月

更新:现在正确的方法是使用剪贴板API。

例如:

// get the text from the DOM Element: 
const textToCopy = document.querySelector('.content').innerText

// when someone clicks on the <a class="copy-text"> element 
// (which should be a <button>), execute the copy command:
document.querySelector('.copy-text').addEventListener('click' , ()=> {
  navigator.clipboard.writeText(textToCopy).then(
    function() {
      /* clipboard successfully set */
      window.alert('Success! The text was copied to your clipboard') 
    }, 
    function() {
      /* clipboard write failed */
      window.alert('Opps! Your browser does not support the Clipboard API')
    }
  )
})

就是这样。

如果你想看看在Clipboard API引入之前的解决方案(现在不是一个好的实践):

$('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;" />

大多数建议的答案都会创建一个额外的临时隐藏输入元素。因为现在大多数浏览器都支持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>


两者都会有魅力:),

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


剪贴板-填充库是现代基于promise的异步剪贴板API的填充库。

在CLI下安装:

npm install clipboard-polyfill 

导入为JS文件中的剪贴板

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

例子

我在一个bundle中使用require("babel-polyfill");并在chrome 67上进行了测试。所有这些都有利于生产。


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


你可以从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();
            }
        };

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

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

这是这个问题最简单的解


纯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>


2023年1月

从2023年开始,你应该使用剪贴板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')
});

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


<p style="color:wheat;font-size:55px;text-align:center;">How to copy a TEXT to Clipboard on a Button-Click</p>
    
    <center>
    <p id="p1">Hello, I'm TEXT 1</p>
    <p id="p2">Hi, I'm the 2nd TEXT</p><br/>
    
    <button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>
    <button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>
      
    </center>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
<script>
    function copyToClipboard(element) {
      var $temp = $("<input>");
      $("body").append($temp);
      $temp.val($(element).text()).select();
      document.execCommand("copy");
      $temp.remove();
    }
</script>

我刚才正在做,我只是想知道有没有比我更好的方法,但是没有。

你可以使用我的代码,它复制文本并显示一个工具提示。

Head

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/remixicon@2.2.0/fonts/remixicon.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Body

<div class="alert alert-primary alert-dismissible mb-0 py-1" role="alert" id="liveAlert">
    <div class="container d-flex justify-content-between">
      <button type="button" class=" btn align-self-center ms-4 copytext" data-bs-toggle="tooltip" data-bs-placement="top" title=""><strong>Good news!</strong>  You just got 10% off, use your coupon <span class="fw-bold bg-secondary text-white px-2 maintext">store10off</span>. <i class="ri-file-copy-line"></i></button>
      <button type="button" class="btn align-self-center" data-bs-dismiss="alert" aria-label="Close"><strong class="fw-bold fs-4"><i class="ri-close-fill"></i></strong></button>
    </div>
    </div>

函数

<script>
    $('.copytext').click(function(){
        var thistooltip = $(this);
        var thistext = $(this).children('.maintext').text();
        navigator.clipboard.writeText(thistext);
        $(this).attr('title','copied');
        setTimeout(function(){$(thistooltip).tooltip("toggle");}, 800);
    });
</script>

非常简单。你必须搜索js navigator.clipboard.writeText("thistext"); 这将简单地复制文本“thistext”。现在让它工作点击,使用jquery onclick函数和存储值(你想复制的文本)在一个字符串(如果你需要,那么你可以使用DOM以及从页面获取一个值),并使用这一行复制,而不是“thistext”,传递变量!


您可以使用导航器简单地执行复制到剪贴板。

navigator.clipboard.writeText("Your text").

 document.getElementById('markup-copy').addEventListener('click', function() {
               var txt = "Your text Here";
                    $("<textarea/>").appendTo("body").val(txt).select().each(function () {
                    document.execCommand('copy');
                }).remove();
            });

下面是多个答案的组合。这将正确地保存换行符。

// Copies a value to the clipboard
    window.copyToClipboard = function(value) {
        // navigator clipboard api needs a secure context (https)
        if (navigator.clipboard && window.isSecureContext) {
            // navigator clipboard api method
            return navigator.clipboard.writeText(value).then(function () {
                //alert('It worked! Do a CTRL - V to paste')
            }, function () {
                alert('Error while copying to clipboard.')
            });
        } else {
            // text area method
            let textArea = document.createElement("textarea");
            textArea.value = value;
            // make the textarea out of viewport
            textArea.style.position = "fixed";
            textArea.style.left = "-999999px";
            textArea.style.top = "-999999px";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            document.execCommand('copy');
            textArea.remove();
        }
    }

纯JS +更多的兼容性

function copyToClipboard(e) { selectText(e); document.execCommand("copy"); } function selectText(e) { e = document.getElementById(e); if (document.body.createTextRange) { const r = document.body.createTextRange(); r.moveToElementText(e); r.select(); } else if (window.getSelection) { const s = window.getSelection(); const r = document.createRange(); r.selectNodeContents(e); s.removeAllRanges(); s.addRange(r); } else { console.warn("Could not select text in "+e+": Unsupported browser."); } } <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/> <span style="border: 1px dotted gray;padding:10px 5px"> <strong style="font-size: 25px; margin-right: 10px" id="clipboard-text">С2Н5ОН</strong> <button onclick="copyToClipboard('clipboard-text')"><i class="fa fa-clipboard"></i></button> </span> <p><input placeholder="paste me here" value="" type="text"><p>


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

HTML:

// you need bootstrap(js && css) and JQuery(js)
<span class="text-copy" value="your-text">text</span>

CSS:

.text-copy {
  cursor: pointer;
  color: #0d6efd;
  text-decoration: underline;
}
.text-copy:hover {
  color: #1b6be4;
}

JS(使用JQuery):

$(document).ready(function() {
  var elements = $('.copy-text');
  for(let i = 0; i < elements.length; i++) {
    const element = $(elements[i]);
    element.attr('data-toggle', 'tooltip')
           .attr('data-placement', 'top')
           .attr('title', `Tab to copy "${element.attr('value')}"`);
  }
  $('[data-toggle="tooltip"]').tooltip();
  $('.text-copy').click(function() {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(this).attr('value')).select();
    document.execCommand("copy");
    $temp.remove();
  });
});

$(document).ready(async function() { var elements = $('.text-copy'); for(let i = 0; i<elements.length; i++) { const element = $(elements[i]); element.attr('data-toggle', 'tooltip') .attr('data-placement', 'top') .attr('title', `Tab to copy "${element.attr('value')}"`); } $('[data-toggle="tooltip"]').tooltip(); $('.text-copy').click(function() { var $temp = $("<input>"); $("body").append($temp); $temp.val($(this).attr('value')).select(); document.execCommand("copy"); $temp.remove(); }); }); body { display: grid; justify-content: center; } .text-copy { cursor: pointer; color: #0d6efd; text-decoration: underline; } .text-copy:hover { color: #1b6be4; } <html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script> </head> <body> <h2 class="text-copy" value="your copy text">your text</h2> <br> <h4>paste here</h4> <input type="text"> </body> </html>


你为什么不直接用这个代码,我不明白?

navigator.clipboard.writeText('text here...');

这是一个优雅的Javascript解决方案

<input type="text" value="Foo Bar" id="your_input">
<button onclick="copy()">Copy text</button>

<script type="application/javascript">
function copy() {
  var copiedtext = document.getElementById("your_input");
  copiedtext.select();
  copiedtext.setSelectionRange(0, 99999); //for mobile devices
  navigator.clipboard.writeText(copiedtext.value);
  alert("You just copied " + copiedtext.value);
}
</script>

使用这个函数:

function copy_input($input) {
        $input.focus();
        $input.select();
        try {  
            var successful = document.execCommand('copy');  
        } catch(err) {  
            console.error('Unable to copy'); 
        }       
    }   

电话:

$(".copy-text").on("click",() => {
    copy_input("#input_Id")
})