兼容写法
htmlcssjs
<div class="button" onclick="nihao()">
<div class="status" id="text">你好啊</div>
</div>
随便写写
function nihao(){
copyToClipboard(document.getElementById("text"));
}
function copyToClipboard(elem) {
// 创建隐藏文本元素(如果它不存在的话)
// 判断是否是输入框,如果不是需要建立新的输入框
var targetId = "_hiddenCopyText_";
var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
var origSelectionStart, origSelectionEnd;
if (isInput) {
// 输入框可直接进行选择和复制
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// 使用临时表单元素进行选择和复制
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement("textarea");
target.style.position = "absolute";
target.style.left = "-9999px";
target.style.top = "0";
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// 选择的内容
var currentFocus = document.activeElement;
target.focus();
target.setSelectionRange(0, target.value.length);
// 复制选择
var succeed;
try {
succeed = document.execCommand("copy");
} catch(e) {
succeed = false;
}
// 恢复原来的焦点
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
}
if (isInput) {
// 恢复之前的选择
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// 清除临时内容
target.textContent = "";
}
return succeed;
}
Comments | NOTHING