兼容多浏览器的原生js复制函数copyText怎么使用
JS复制文本到剪切板 copyText
www.baidu.com
删减后的代码,减少了判断,其实上面的代码是非常好的
function copyText (text) {
//生成一个textarea对象
var textArea = document.createElement('textarea');
//设置属性
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
textArea.style.width = '2em';
textArea.style.height = '2em';
textArea.style.padding = 0;
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
textArea.value = text;
//添加到页面body
document.body.appendChild(textArea);
textArea.select();
//执行
var msg = document.execCommand('copy') ? '成功' : '失败';
Popup('复制内容' + msg);
//移除对象
document.body.removeChild(textArea);
}
function Popup(message){
var span=document.createElement('span')
span.innerHTML=message || 'default'
span.className='popupStyle'
span.style.display='block'
document.body.appendChild(span)
setTimeout(()=>{
span.remove()
},1000)
}对了不要忘了css样式
.popupStyle{
width:180px;
height:50px;
background-color: rgb(85,85,85);
/* display:none; */
color:#fff;
text-align:center;
line-height:50px;
border-radius:5px;
padding:0;
position:fixed;
z-index:1;
top:30%;
left:50%;
transform:translateX(-50%);
}