手写常用js工具函数–剪切内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简易剪贴板</title>
</head>
<body>
<button id="btn">点击复制</button>
<script>
let btn = document.getElementById('btn')
btn.addEventListener('click',copyValue,true)
function copyValue(){
let targetInput = document.createElement('input')
targetInput.style.position = 'absolute'
targetInput.style.left = '-99999px'
targetInput.style.top = '-99999px'
targetInput.id = 'test'
targetInput.value = btn.innerHTML
document.body.appendChild(targetInput)
document.getElementById('test').addEventListener('copy',getTargetValue,true)
document.getElementById('test').select()
document.execCommand('copy',true)
if(document.getElementById('test')){
let box = document.getElementById('test')
box.parentNode.removeChild(box)
}
function getTargetValue(e){
if(isIE()){
if(window.clipboardData){
window.clipboardData.setData('Text',e.target.value)
}
}else{
e.preventDefault()
if(e.clipboardData){
e.clipboardData.setData('text/plain',e.target.value)
}
}
}
}
function isIE () {
var input = window.document.createElement('input')
if (window.ActiveXObject === undefined) return null
if (!window.XMLHttpRequest) return 6
if (!window.document.querySelector) return 7
if (!window.document.addEventListener) return 8
if (!window.atob) return 9
if (!input.dataset) return 10; return 11
}
</script>
</body>
</html>