这个功能第一次做,开始以为很难得样纸,但是后来,发现其实也很简单哒,哈哈哈.为什么简单呢?看下面大家就知道啦,嘿嘿
1.html部分
<meta charset="UTF-8">
<span id="demoInput">hello,world</span>
<button style="background-color: antiquewhite;display: inline;" id="btn">copySku</button>
2.js代码部分
<script>
var btn = document.querySelector('#btn');
btn.addEventListener('click', function(){
var input = document.createElement('input');
document.body.appendChild(input);
var content = document.querySelector('#demoInput').innerHTML;
input.setAttribute('value', content);
input.select();
if (document.execCommand('copy')) {
document.execCommand('copy'); #execCommand()这个方法,只对可编辑区域有效果,如 input ,textarea 标签,
console.log('复制成功');
}
document.body.removeChild(input);
})
</script>