[英]How to copy to the clipboard in JavaScript. Including the value in the data-value
這是一個相當普遍的問題,但我還沒有找到一個簡單的答案。 由於我不會寫答案,所以我會寫一個問答。 這是stackoverflow上的第一篇文章,請不要嚴格判斷:)
<span class="contacts-link" id="CopyMail" data-value="test@stackoverflow.com"></span>
<span class="link" onClick="copyClipboard()">Copy Hidden Text</span>
<style>
.contacts-link {
display: none;
}
.link {
background: #000000;
color: white;
padding: 25px;
font-size: 32px;
cursor: pointer;
}
.link:hover {
background-color: #ff5722;
}
.link:active {
padding: 30px;
}
</style>
<script>
function copyClipboard() {
const str = document.getElementById("CopyMail").getAttribute("data-value");
const element = document.createElement("textarea");
element.value = str;
element.setAttribute("readonly", "");
element.style.position = "absolute";
element.style.left = "-9999px";
document.body.appendChild(element);
element.select();
document.execCommand("copy");
document.body.removeChild(element);
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.