我想将HTML复制到剪贴板。此示例应复制tagHolder
中的按钮,但它复制了<span style="font-family: Arial; font-size: 13.3333px; text-align: center; background-color: rgb(221, 221, 221);">button</span>
。相反(在Chrome中(,我需要它复制tagHolder
的innerHTML
,即<button>button</button>
。
function $id(id) {
return document.getElementById(id);
}
function doCopy() {
var tagHolder = $id('tagHolder');
tagHolder.style.visibility = '';
copy(tagHolder)
tagHolder.style.visibility = 'hidden';
}
function showCode() {
var code = $id("xxx").innerHTML;
$id("txtinfo").innerText = code;
}
function copy(element) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNodeContents(element);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
document.execCommand("Copy");
}
<!DOCTYPE html>
<html>
<body>
<button onclick="doCopy()">copy</button><br />
paste:<br />
<div id="xxx" contenteditable="true" onpaste="setTimeout(showCode, 1);" style="border: 1px solid black;"></div>
html:<br />
<div id="txtinfo" style="border: 1px solid black;"></textarea>
<div id="tagHolder" style="visibility: hidden;"><button>button</button></div>
</body>
</html>
在Davidwalsh的博客中使用clipboardjs作为演示
function $id(id) {
return document.getElementById(id);
}
function doCopy() {
var clipboard = new ClipboardJS('.tagHolder');
}
function showCode() {
var code = $id("xxx").innerHTML;
$id("txtinfo").innerText = code;
}
function $id(id) {
return document.getElementById(id);
}
function doCopy() {
var clipboard = new ClipboardJS('.tagHolder');
}
function showCode() {
var code = $id("xxx").innerHTML;
$id("txtinfo").innerText = code;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js"></script>
<button onclick="doCopy()">copy</button><br /> paste:
<br />
<div id="xxx" contenteditable="true" onpaste="setTimeout(showCode, 1);" style="border: 1px solid black;"></div>
html:<br />
<div id="txtinfo" style="border: 1px solid black;"></div>
<div class="tagHolder" data-clipboard-action="copy" data-clipboard-target="#xxx" style="visibility: hidden;"><button>button</button></div>