Я просмотрел кучу ответов и статей, в которых показано, как копировать текст при нажатии кнопки с помощью jquery, но ни одна из них не сработала для меня. Я добавляю значение через ajax в DOM, и я хотел бы, чтобы это было скопировано по нажатию кнопки.
Все эти решения работают на chrome и работают в сафари (версия: 13.0 .5) если используется jsfiddle / codepen, но они не работают в сафари при использовании через отдельный файл html и js, в любом случае, в моем случае.
Сначала я попытался сделать невидимый ввод с позицией : absolute и left: -99999 и выделил текст в нем с помощью jquery и использовал execCommand ("copy") ;. Это не сработало. Я также попробовал ответы, упомянутые здесь: Javascript Копировать в буфер обмена на Safari?
Я также попробовал две функции, упомянутые ниже, но не повезло. В дополнение к этим функциям я также попробовал каждый плагин javascript, который смог найти, и он тоже не работал.
function 1:
function copy(value, showNotification, notificationText) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val(value).select();
document.execCommand("copy");
$temp.remove();
$(".copyfrom").val(value)
$(".copyfrom").select();
document.execCommand("copy");
//trigger animation---
if (typeof showNotification === 'undefined') {
showNotification = true;
}
if (typeof notificationText === 'undefined') {
notificationText = "Copied to clipboard";
}
var notificationTag = $("div.copy-notification");
if (showNotification && notificationTag.length == 0) {
notificationTag = $("<div/>", { "class": "copy-notification", text: notificationText });
$("body").append(notificationTag);
notificationTag.fadeIn("slow", function () {
setTimeout(function () {
notificationTag.fadeOut("slow", function () {
notificationTag.remove();
});
}, 1000);
});
}
}
function2:
function copyToClipboard(textToCopy) {
var textArea;
function isOS() {
return navigator.userAgent.match(/ipad|iphone/i);
}
function createTextArea(text) {
textArea = document.createElement('textArea');
textArea.readOnly = true;
textArea.contentEditable = true;
textArea.value = text;
document.body.appendChild(textArea);
}
function selectText() {
var range, selection;
if (isOS()) {
range = document.createRange();
range.selectNodeContents(textArea);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
textArea.setSelectionRange(0, 999999);
} else {
textArea.select();
}
}
function copyTo() {
document.execCommand('copy');
document.body.removeChild(textArea);
}
createTextArea(textToCopy);
selectText();
copyTo();
//trigger animation---
if (typeof showNotification === 'undefined') {
showNotification = true;
}
if (typeof notificationText === 'undefined') {
notificationText = "Copied to clipboard";
}
var notificationTag = $("div.copy-notification");
if (showNotification && notificationTag.length == 0) {
notificationTag = $("<div/>", { "class": "copy-notification", text: notificationText });
$("body").append(notificationTag);
notificationTag.fadeIn("slow", function () {
setTimeout(function () {
notificationTag.fadeOut("slow", function () {
notificationTag.remove();
});
}, 1000);
});
}
}
Вот мои ajax и html:
$(".fa-link").on("click", function () {
var mlink = $(".boxmlink").attr("href").trim()
var fetchWallID = new XMLHttpRequest()
fetchWallID.open("POST", db, true);
fetchWallID.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
fetchWallID.onload = function () {
if (this.status == 200) {
var url = $(location).attr("href").split("?")
var id = (this.responseText).trim()
var windowurl = url[0].trim()
var finalurl = (windowurl + '?wallid=' + id).trim().replace("#", '')
//copy(finalurl, true)
//copyToClipboard(finalurl)
}
}
fetchWallID.send("mlinkID=" + mlink)
})
html:
<a href="#" class="fa fa-link"></a>