主要使用 document.execCommand('copy')
实现内容的复制。
情况:
- 复制表单元素,如 input textarea元素中的内容。
- 复制如 div,span 元素中的内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="div">this is a div</div><br/>
<textarea id="textarea">this is a textarea</textarea><br/>
<input id="input" value="this is a input"/><br/>
<button onclick="copy('div')">复制div内容</button>
<button onclick="copy('textarea')">复制textarea内容</button>
<button onclick="copy('input')">复制input内容</button>
</body>
<script>
function copy(id) { // 复制指定元素中的文本内容
const el = document.getElementById(id);
if (!el) {
throw new TypeError(`${id}的元素不存在!`);
}
const tagName = el.tagName;
const formElList = ['input', 'textarea'];
if (formElList.includes(tagName.toLowerCase())) { // 表单元素,如:input, textarea
el.focus();
if (el.setSelectionRange) {
el.setSelectionRange(0, el.value.length);
} else {
el.select();
}
} else { // 非表单元素,如:div, span 等
if (document.selection) { // IE
const range = document.body.createTextRange();
range.moveToElementText(el);
range.select();
} else if (window.getSelection) { // 非IE
const selection = window.getSelection();
const range = document.createRange();
selection.removeAllRanges();
range.selectNodeContents(el);
selection.addRange(range);
}
}
document.execCommand('copy');
}
</script>
</html>