如何将div内的文本复制到剪贴板?我有一个div,需要添加一个链接,将文本添加到剪贴板。有解决办法吗?
<p class="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>
<a class="copy-text">copy Text</a>
在我点击复制文本,然后我按Ctrl + V,它必须被粘贴。
大多数建议的答案都会创建一个额外的临时隐藏输入元素。因为现在大多数浏览器都支持div内容编辑,所以我提出了一个解决方案,它不创建隐藏元素,保留文本格式,并使用纯JavaScript或jQuery库。
下面是一个使用我能想到的最少代码行的极简框架实现:
//Pure javascript implementation:
document.getElementById("copyUsingPureJS").addEventListener("click", function() {
copyUsingPureJS(document.getElementById("copyTarget"));
alert("Text Copied to Clipboard Using Pure Javascript");
});
function copyUsingPureJS(element_id) {
element_id.setAttribute("contentEditable", true);
element_id.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
element_id.focus();
document.execCommand("copy");
element_id.removeAttribute("contentEditable");
}
//Jquery:
$(document).ready(function() {
$("#copyUsingJquery").click(function() {
copyUsingJquery("#copyTarget");
});
function copyUsingJquery(element_id) {
$(element_id).attr("contenteditable", true)
.select()
.on("focus", function() {
document.execCommand('selectAll', false, null)
})
.focus()
document.execCommand("Copy");
$(element_id).removeAttr("contenteditable");
alert("Text Copied to Clipboard Using jQuery");
}
});
#copyTarget {
width: 400px;
height: 400px;
border: 1px groove gray;
color: navy;
text-align: center;
box-shadow: 0 4px 8px 0 gray;
}
#copyTarget h1 {
color: blue;
}
#copyTarget h2 {
color: red;
}
#copyTarget h3 {
color: green;
}
#copyTarget h4 {
color: cyan;
}
#copyTarget h5 {
color: brown;
}
#copyTarget h6 {
color: teal;
}
#pasteTarget {
width: 400px;
height: 400px;
border: 1px inset skyblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="copyTarget">
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
<strong>Preserve <em>formatting</em></strong>
<br/>
</div>
<button id="copyUsingPureJS">Copy Using Pure JavaScript</button>
<button id="copyUsingJquery">Copy Using jQuery</button>
<br><br> Paste Here to See Result
<div id="pasteTarget" contenteditable="true"></div>