js 复制功能

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/skying8603/article/details/83945072
示例代码1

<html>
<head>
<title>JS复制当前URL</title>
<script type="text/javascript">
copyClipboard=function(txt){
if(window.clipboardData){
window.clipboardData.clearData();
window.clipboardData.setData("Text",txt);
}else if(navigator.userAgent.indexOf("Opera")!=-1){
window.location=txt;
}else if(window.netscape){
try{
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}catch(e){
alert("您的firefox安全限制限制您进行剪贴板操作,请打开’about:config’将 signed.applets.codebase_principal_support’设置为true’之后重试,相对路径为firefox根目录 /greprefs/all.js");
return false;
}
var clip=Components.classes['@mozilla.org/widget/clipboard;1'].createInstance (Components.interfaces.nsIClipboard);
if(!clip)return;
var trans=Components.classes['@mozilla.org/widget/transferable;1'].createInstance (Components.interfaces.nsITransferable);
if(!trans)return;
trans.addDataFlavor('text/unicode');
var str=new Object();
var len=new Object();
var str=Components.classes["@mozilla.org/supports-string;1"].createInstance (Components.interfaces.nsISupportsString);
var copytext=txt;
str.data=copytext;
trans.setTransferData("text/unicode",str,copytext.length*2);
var clipid=Components.interfaces.nsIClipboard;
if(!clip)return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}

function copyUserHomeToClipBoard(){
var clipBoardContent = document.URL;
var clipBoardTitle = document.title;
if(copyClipboard('ddddddddddddddddddddddddddddddddddddaaaa')!=false){
alert("复制成功,请粘贴到你的QQ/MSN上推荐给你的好友!\r\n\r\n内容如下:\r\n"+clipBoardTitle+clipBoardContent);
}
}
</script>
</head>
<body>
<div>
<input type="button" value="Copy" οnclick="copyUserHomeToClipBoard();"/>
</div>
</body>
</html>

示例代码2

<html>
<head>
<title>JS复制</title>
<script type="text/javascript">
function copyText(id) {
var targetText = document.getElementById(id);
try {
var clipText = targetText.createTextRange();
clipText.execCommand("Copy");
alert('复制成功,可以按Ctrl+V粘贴');
} catch(e) {
targetText.focus();//获得焦点
targetText.select();//选中文本
alert('您的浏览器不支持剪贴板复制,\n请按Ctrl+C复制链接。');
}
}
</script>
</head>
<body>
<div>
<input id="shareUrl" value="http://chenfeng0104.iteye.com" style="width:260px;"/>
<input type="button" value="Copy" οnclick="copyText('shareUrl');"/>
</div>
</body>
</html>
展开阅读全文

没有更多推荐了,返回首页