我使用此代码将文本从“div1”id 复制到剪贴板。它有效,但是当我选择页面中的其他文本并点击复制文本按钮时,它会复制所选文本而不是 div1 id 文本。我每次都需要复制 div1 id 文本。怎么了?
<?php
echo <div id="div2">
'<button class="btn-light" id="button1" onclick="CopyToClipboard(\'div1\')"
data-toggle="tooltip" title="Copy">Copy the text</button>
<div id="div1" > ';
echo "copy it";
echo '</div>';
echo '</div>';
?>
<script type='text/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("Copied")
</script>
最佳答案
这可能有用。我正在使用 FireFox,尽管它会取消选择其他选择,选择您的 div,然后将其复制到剪贴板。我想有一种方法可以执行副本,然后将内容返回到执行函数之前的状态。
function CopyToClipboard(containerid) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().empty();
window.getSelection().addRange(range);
}
document.execCommand("Copy");
}
<div id="div2">
<button class="btn-light" id="button1" onclick="CopyToClipboard('div1')" data-toggle="tooltip" title="Copy">Copy the text</button>
<div id="div1" >copy it</div>
<div id="div3">Other Text</div>
</div>
关于javascript复制到剪贴板功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56827929/