gpt4 book ai didi

Javascript 在 safari 上复制到剪贴板?

转载 作者:数据小太阳 更新时间:2023-10-29 04:04:09 28 4
gpt4 key购买 nike

这可能是重复的问题,但我没有找到解决方案。

我正在尝试在单击按钮时复制文本。它在 chrome、mozilla 上工作(在 windows 和 mac 上工作,但不在 linux 上工作)。它不适用于 safari。

我正在使用 document.execCommand("copy") 命令进行复制。

safari 支持这个命令吗?

有什么办法可以支持所有浏览器吗?

最佳答案

请检查我的解决方案。

它适用于 Safari(在 iPhone 7 和 iPad 上测试过)和其他浏览器。

window.Clipboard = (function(window, document, navigator) {
var textArea,
copy;

function isOS() {
return navigator.userAgent.match(/ipad|iphone/i);
}

function createTextArea(text) {
textArea = document.createElement('textArea');
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 copyToClipboard() {
document.execCommand('copy');
document.body.removeChild(textArea);
}

copy = function(text) {
createTextArea(text);
selectText();
copyToClipboard();
};

return {
copy: copy
};
})(window, document, navigator);

// How to use
Clipboard.copy('text to be copied');

https://gist.github.com/rproenca/64781c6a1329b48a455b645d361a9aa3 https://fiddle.jshell.net/k9ejqmqt/1/

希望对你有帮助。

问候。

关于Javascript 在 safari 上复制到剪贴板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40147676/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com