1 回答
TA贡献1865条经验 获得超7个赞
这并不是说您必须清除剪贴板,而是您需要清除选择。这个答案涵盖了这一点:
使用 JavaScript 清除文本选择
我已经对你的代码片段进行了更改,并且它正在工作(至少对我来说,在 chrome 上)
function copy_snippet(snippet){
if(document.selection){
document.selection.empty();
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(snippet));
range.select().createTextRange();
document.execCommand("copy");
}else if(window.getSelection){
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
var range = document.createRange();
range.selectNode(document.getElementById(snippet));
window.getSelection().addRange(range);
document.execCommand("copy");
}
}
<div id="1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam et tempus lacus, at congue augue. Vivamus nisl diam, ornare non justo vel, pulvinar gravida magna. Nullam posuere pharetra felis, sit amet viverra ex bibendum ut. Cras hendrerit tempor metus ut interdum. Suspendisse potenti. Etiam mi nunc, lacinia non justo vel, eleifend lobortis lectus. Morbi nulla diam, volutpat quis mauris ut, ultrices venenatis massa.
</div>
<button onclick="copy_snippet('1');">Copy</button>
<br /><br />
<div id="2">
Vestibulum est arcu, porttitor a leo in, rhoncus mattis elit. In hac habitasse platea dictumst. Praesent vitae felis vitae risus ornare mattis. Maecenas ac condimentum lorem. Proin ornare nisi non sapien accumsan, quis suscipit est pellentesque. Sed enim purus, auctor sit amet tincidunt id, convallis a eros. Aenean a rhoncus orci. Pellentesque consequat ligula tincidunt semper varius.
</div>
<button onclick="copy_snippet('2');">Copy</button>
添加回答
举报