2 回答

TA貢獻1886條經驗 獲得超2個贊
這是一個例子:
copyLink (url) {
const el = document.createElement('textarea');
el.value = url;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
},

TA貢獻1799條經驗 獲得超8個贊
好吧,對于您提到的代碼部分,您需要在代碼庫中更改更多代碼。
首先你需要知道
$("<input>")
將創建一個輸入元素,它在普通 javascript 中的等價物是document.createElement("input")
.$temp.val(value).select();
將在一行中執行兩個操作,首先設置函數value
參數input
值,最后將通過select()
. 因此,要將其翻譯成 javascript,我們需要執行以下兩個操作:
$temp.value = value; $temp.select();
最后,您需要使用
remove()
而不是刪除該輸入元素removeElement()
。
最終結果將是這樣的:
document.querySelector("#copymanager").addEventListener("click", (e) => {
e.preventDefault();
CopyToClipboard(document.location.href, true, "Value copied");
});
function CopyToClipboard(value, showNotification, notificationText) {
var $temp = document.createElement("input");
document.body.append($temp);
$temp.value = value;
$temp.select();
document.execCommand("copy");
$temp.remove();
if (typeof showNotification === "undefined") {
showNotification = true;
}
if (typeof notificationText === "undefined") {
notificationText = "Copied to clipboard";
}
var notificationTag = document.createElement("div");
notificationTag.className = "copy-notification";
notificationTag.innerText = notificationText;
if (showNotification) {
document.body.append(notificationTag);
notificationTag.style.display = "block";
notificationTag.style.transition = "opacity 1s";
setTimeout(function() {
notificationTag.style.opacity = "0";
notificationTag.remove();
}, 1000);
}
}
.copy-notification {
color: #ffffff;
background-color: rgba(0, 0, 0, 0.8);
padding: 20px;
border-radius: 30px;
position: fixed;
top: 50%;
left: 50%;
width: 150px;
margin-top: -30px;
margin-left: -85px;
display: none;
text-align: center;
}
<button id="copymanager">Click to copy to clipboard</button>
現場演示: codepen.io
添加回答
舉報