现在的位置: 首页 > 综合 > 正文

JS复制内容到剪贴板(兼容FF/Chrome/Safari所有浏览器)

2018年05月07日 ⁄ 综合 ⁄ 共 1527字 ⁄ 字号 评论关闭

1、对于IE来说,把内容复制到剪切板很容易:

function copyCont(_name) {
window.clipboardData.clearData(); 
window.clipboardData.setData("Text", _name);
}


2、兼容所有浏览器的方法:使用ZeroClipboard组件

这个方法原理是在一个透明的flash(对用户来说是不可见的)上覆盖一个dom元素比如button或div,当点击这个dom时,实际点击的是flash,从而访问flash的剪贴板。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js代码ZeroClipboard组件复制剪切板兼容firefox,Chrome,IE</title>
</head>
 
<body>
 
<style type="text/css"> 
*{margin:0;padding:0;list-style-type:none;}
a,img{border:0;}
body{font:12px/180% Arial, Helvetica, sans-serif ,"新宋体";}
.demo{width:680px;margin:40px auto 0 auto;}
.demo td{padding:5px;}
#copy-button{width:125px;height:45px;cursor:pointer;border:0;background:url(images/btn.gif) no-repeat;}
</style>
 
<div class="demo">
<table width="100%">
<tr>
<td>
<textarea id="copytext" name="codeiframe" rows="5" cols="60">复制的内容。。。</textarea>
</td>
</tr>
<tr>
<td><input type="button" value="" id="copy-button" /></td>
</tr>
</table>
</div>
 
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/ZeroClipboard.js"></script>
<script type="text/javascript"> 
var clip = null;
ZeroClipboard.setMoviePath("swf/ZeroClipboard.swf");
$(document).ready(function(){
clip = new ZeroClipboard.Client();  
clip.setHandCursor(true);  
clip.setText($("#copytext").val());  
clip.glue("copy-button");
clip.addEventListener("complete", function(){
alert("代码已复制到剪贴板!");
});
});
</script>
 
</body>
</html>

抱歉!评论已关闭.