我有这样的 JS 代码,您只需传递一个元素的 ID,它就会从该元素复制文本。但是,当我在一页上有多个片段并且想要复制多个片段时,它就不起作用了。
在第一页加载时,我可以复制一个片段,之后的每个片段都未正确复制,我是否必须清除第一个片段中的剪贴板?
function copy_snippet(snippet) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(snippet));
range.select().createTextRange();
document.execCommand("copy");
} else if (window.getSelection) {
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>
鸿蒙传说
相关分类