<!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>
复制代码