38 lines
1.2 KiB
JavaScript
38 lines
1.2 KiB
JavaScript
(function () {
|
|
"use strict";
|
|
|
|
function fallbackCopy(value) {
|
|
var input = document.createElement("textarea");
|
|
input.value = value;
|
|
input.setAttribute("readonly", "");
|
|
input.style.position = "fixed";
|
|
input.style.opacity = "0";
|
|
document.body.appendChild(input);
|
|
input.select();
|
|
var copied = document.execCommand("copy");
|
|
input.remove();
|
|
return copied;
|
|
}
|
|
|
|
function copyValue(value) {
|
|
if (navigator.clipboard && window.isSecureContext) {
|
|
return navigator.clipboard.writeText(value);
|
|
}
|
|
return fallbackCopy(value) ? Promise.resolve() : Promise.reject(new Error("copy failed"));
|
|
}
|
|
|
|
document.addEventListener("click", function (event) {
|
|
var button = event.target.closest("[data-copy-value]");
|
|
if (!button) return;
|
|
var value = button.getAttribute("data-copy-value") || window.location.href;
|
|
var original = button.textContent;
|
|
copyValue(value).then(function () {
|
|
button.textContent = "已复制";
|
|
window.setTimeout(function () { button.textContent = original; }, 1600);
|
|
}).catch(function () {
|
|
button.textContent = "复制失败";
|
|
window.setTimeout(function () { button.textContent = original; }, 1600);
|
|
});
|
|
});
|
|
})();
|