<input type="text" id="input">
<button onclick="copyText(document.getElementById('input').value)">复制文本</button>
<script>
//1.通常写法
function copyText(text) {
if (navigator.clipboard) {
navigator.clipboard.writeText(text);
} else {
var input = document.createElement('input');
input.setAttribute('value', text);
document.body.appendChild(input);
input.select();
document.execCommand('copy');
document.body.removeChild(input);
}
}
//2.惰性函数写法 一旦确定下来、就固定下来
function copyText(text) {
if (navigator.clipboard) {
copyText = (text) => {
navigator.clipboard.writeText(text);
}
} else {
function copyText(text) {
var input = document.createElement('input');
input.setAttribute('value', text);
document.body.appendChild(input);
input.select();
document.execCommand('copy');
document.body.removeChild(input);
}
}
copyText(text);
}
//3.函数进阶写法
function createCopyText() {
if (navigator.clipboard) {
return (text) => {
navigator.clipboard.writeText(text);
}
} else {
return (text) => {
var input = document.createElement('input');
input.setAttribute('value', text);
document.body.appendChild(input);
input.select();
document.execCommand('copy');
document.body.removeChild(input);
}
}
};
const copyText = createCopyText();
//4.永远不变的立即执行写法
const copyText = (function () {
if (navigator.clipboard) {
return (text) => {
navigator.clipboard.writeText(text);
}
} else {
return (text) => {
var input = document.createElement('input');
input.setAttribute('value', text);
document.body.appendChild(input);
input.select();
document.execCommand('copy');
document.body.removeChild(input);
}
}
})();
</script>
Last modification:November 7, 2023
© Allow specification reprint