我使用此代码将“ 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>
答案 0 :(得分:1)
我希望我能正确解释您的问题。将div复制到剪贴板后,可以对其进行修改以保留原始选择。足够快,用户甚至可能会注意到。
var savedSelection;
function CopyToClipboard(containerid) {
if (window.getSelection) {
var sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
savedSelection = sel.getRangeAt(0);
}
} else if (document.selection && document.selection.createRange) {
savedSelection = document.selection.createRange();
}
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");
if (savedSelection) {
if (window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(savedSelection);
} else if (document.selection && savedSelection.select) {
savedSelection.select();
}
}
}
<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>
<p>
Other Text for testing restoration.
</p>
答案 1 :(得分:0)
这可能有效。我正在使用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>