<!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>Document</title>
</head>
<body>
<div style="margin-top:50px;">
<!-- <input id='copyText' value="我是要模拟复制的内容" style='opacity: 0;position: absolute;' type="text">
<input value="我是要模拟复制的内容" disabled type="text"> -->
<input id="copyText" type="text" value="我是要模拟复制的内容">
<button class="btnText">copy</button>
</div>
</body>
<script>
function copyTextarea(id) {
let target = null
target = document.querySelector('#' + id)
target.select()
let copyResult = document.execCommand('copy')
window.getSelection().removeAllRanges()
if (copyResult) {
console.log('复制成功')
} else {
console.log('复制失败')
}
}
let btnText = document.querySelector('.btnText')
btnText.addEventListener('click', (e) => {
copyTextarea('copyText')
})
</script>
</html>
不能复制成功的原因:
1、input框不能有disabled属性;
2、根据第一条扩展,input的width || height 不能为0;
3、input框不能有hidden属性;
4、ID名称要唯一;
网友评论