日期:2014-05-16  浏览次数:20368 次

js 复制功能
示例代码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" onclick="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" onclick="copyText('shareUrl');"/>
</div>
</body>
</html>