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


当前回答

使用这个函数:

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

其他回答

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

编辑截止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中部分实现,但我还没有证实这一点。

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;" />

jQuery简单解决方案。

应由用户点击触发。

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

文本复制是在文本输入,如:< 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>在我们的页面上。