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
添加回答
举报