您的位置:首页 > Web前端 > JavaScript

JS实现复制div(span)的内容到剪切板

2017-09-17 00:55 459 查看
JS实现复制Div(span)的内容到剪切板

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS实现复制Div(span)的内容到剪切板</title>
<script>

function execClick(){
document.execCommand("copy");
}

function execCopy(event,thisDiv){
if(isIE()){
if(window.clipboardData){
window.clipboardData.setData("Text", thisDiv.textContent);
alert(window.clipboardData.getData("Text"));
}
}else{
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData("text/plain", thisDiv.textContent);
alert(event.clipboardData.getData("text"));
}
}
}

function isIE(){
var input = window.document.createElement ("input");
//"!window.ActiveXObject" is evaluated to true in IE11
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;
//"!window.document.body.dataset" is faster but the body is null when the DOM is not
//ready. Anyway, an input tag needs to be created to check if IE is being
//emulated
if (!input.dataset) return 10;
return 11;
}

</script>
</head>
<body>

<div id="thisDiv" onclick="execClick();" oncopy="execCopy(event,this);">这里是DIV的内容</div>

</body>
</html>


参考地址:https://stackoverflow.com/questions/45071353/javascript-copy-text-string-on-click

http://caibaojian.com/detect-ie-version.html

另外,某些浏览器为了安全不允许JS脚本访问剪切板,比如FireFox29版本(但FireFox41版本之后就允许了)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: