angular serve
;
(function(app) {
app.service('ClipBoard', ['URL', '$rootScope',
function(URL, $rootScope) {
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);
textArea.setAttribute('readonly', 'readonly');
}
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() {
try {
if (document.execCommand("Copy")) {
$rootScope.$emit('show-alert', '複製成功');
} else {
$rootScope.$emit('show-alert', '複製失敗!請手動複製!');
}
} catch (err) {
$rootScope.$emit('show-alert', '複製失敗!請手動複製!');
}
document.body.removeChild(textArea);
}
this.copy = function(text) {
createTextArea(text);
selectText();
copyToClipboard();
};
}
])
})(app);
複製代碼
原生js
function copyFun() {
window.Clipboardes = (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);
textArea.setAttribute('readonly', 'readonly');
}
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() {
try {
if (document.execCommand("Copy")) {
$rootScope.$emit('show-alert', '複製成功');
} else {
$rootScope.$emit('show-alert', '複製失敗!請手動複製!');
}
} catch (err) {
$rootScope.$emit('show-alert', '複製失敗!請手動複製!');
}
document.body.removeChild(textArea);
}
copy = function(text) {
createTextArea(text);
selectText();
copyToClipboard();
};
return {
copy: copy
};
})(window, document, navigator);
}
```複製代碼