我在每个内部生成多个具有不同信息的div,我正在尝试使用一个复制div内容的按钮。
下面的代码将复制div中的所有内容,包括按钮的文本。
<script type="text/javascript">
function copyText(event) {
try {
var element = event.parentNode;
if (document.body.createTextRange) { // ie
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
document.execCommand("Copy");
//setInterval(function () { selection.removeAllRanges(); }, 1000);
alert('Copied successfully');
} else if (window.getSelection) { // moz, opera, webkit
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("Copy");
selection.removeAllRanges();
//setInterval(function () { selection.removeAllRanges(); }, 1000);
alert('Copied successfully');
}
}
catch (e) {
alert('Not copied successfully - ' + e.message);
}
}
</script>
<div class="divCard">
Value1: <%=result("Value1")%><br /><br />
Value2: <%=result("Value2")%><br /><br />
<input type="button" id="btnCopytext" onclick="copyText(this)" value="Copy Text" />
</div>
当前输出:
Val1 Val2 Copy Text
期望的输出:
Val1 Val2
如何复制除btn文本以外的所有内容?
另外,有没有办法在复制的内容的末尾修剪空格?
答案 0 :(得分:0)
如何将要复制的内容包装在id中并将该元素传递给复制?
<div class="divCard">
<div id='copythis'>
Value1: <%=result("Value1")%><br /><br />
Value2: <%=result("Value2")%><br /><br />
</div>
<input type="button" id="btnCopytext" value="Copy Text" />
</div>
JS:
function copyText(event) {
try {
var element = document.getElementById("copythis");
if (document.body.createTextRange) { // ie
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
document.execCommand("Copy");
alert('Copied successfully');
} else if (window.getSelection) { // moz, opera, webkit
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("Copy");
selection.removeAllRanges();
alert('Copied successfully');
}
}
catch (e) {
alert('Not copied successfully - ' + e.message);
}
}
document.getElementById("btnCopytext").addEventListener("click",copyText)