<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
//定義函式
window.Clipboard = (function(window, document, navigator) {
var textArea,
copy;
// 判斷是不是ios端
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() {
try {
if(document.execCommand("Copy")) {
console.log("複製成功!");
} else {
console.log("複製失敗!請手動複製!");
}
} catch(err) {
console.log("複製錯誤!請手動複製!")
}
document.body.removeChild(textArea);
}
copy = function(text) {
createTextArea(text);
selectText();
copyToClipboard();
};
return {
copy: copy
};
})(window, document, navigator);
</script>
</head>
<body>
<input id="demoInput" value="hello world">
<button id="btn">點我複製</button>
<script type="text/javascript">
const btn = document.querySelector('#btn');
btn.addEventListener('click', () => {
const input = document.querySelector('#demoInput');
Clipboard.copy(input.value+"複製地址:"+window.location.href);
})
</script>
</body>
</html>
複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input id="demoInput" value="hello world">
<button id="btn">點我複製</button>
</body>
<script type="text/javascript">
const btn = document.querySelector('#btn');
btn.addEventListener('click', () => {
const input = document.querySelector('#demoInput');
input.select();
if(document.execCommand('copy')) {
document.execCommand('copy');
console.log('複製成功');
}
})
</script>
</html>
複製程式碼