您的位置:首页 > 其它

兼容多浏览器的网页复制插件(ZeroClipboard)

2014-03-13 17:05 417 查看
前言:

常规利用JS编写的网页复制功能是最简单的方法,但是只对IE有效,无法做到兼容其它浏览器,对其他浏览器也就只能弹窗提示用户手动复制了。

<script type="text/javascript">
function copyToClipBoard(t) {
if (isIE()) {
var clipBoardContent = "";
if (t == 1) {
clipBoardContent = document.getElementById("wz_contents").value;
} else {
clipBoardContent = document.getElementById("tp_contents").value;
}
clipboardData.setData("Text", clipBoardContent);
alert("您已成功复制了此地址");
}
else {
if (t == 1) {
document.getElementById("wz_contents").select();
} else {
document.getElementById("tp_contents").select();
}
alert("当前浏览器不支持此功能,请按Ctrl+C进行复制!");
}
return true;
}
function isIE(number) {
if (typeof (number) != number) {
return !!document.all;
}
}
</script>


这种方法是很简单,但是用户体验很不好。使用一种能兼容多种主流浏览器的复制功能就很有必要了。

解决方法:使用ZeroClipboard插件和Jquery实现复制功能

ZeroClipboard是利用flash为媒介实现兼容各浏览器复制功能一款jquery插件可以兼容ie6.0及以上版本浏览器、chrome内核浏览器、firefox内核浏览器等。

实例代码:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="jquery.js"></script>//1. 引入jquery文件
</head>
<body>
<div class="demo-area">
<button id="d_clip_button" class="my_clip_button" title="Click me to copy to clipboard." data-clipboard-target="fe_text" data-clipboard-text="Default clipboard text from attribute"><b>Copy To Clipboard...</b></button>
<h4><label for="fe_text">Change Copy Text Here</label></h4>
<textarea id="fe_text"  cols="50" rows="3">Copy me!</textarea>
</div>
<h4>Debug Console:</h4>
<div id="d_debug"></div>

<!--2. 导入ZeroClipboard.min.js文件-->
<script type="text/javascript" src="ZeroClipboard.min.js"></script>
<script language="JavaScript">

$(document).ready(function() {
var clip = new ZeroClipboard($("#d_clip_button"), {
moviePath: "ZeroClipboard.swf"
});

clip.on('load', function (client) {
debugstr("Flash movie loaded and ready.");
});

clip.on('noFlash', function (client) {
$(".demo-area").hide();
debugstr("Your browser has no Flash.");
});

clip.on('wrongFlash', function (client, args) {
$(".demo-area").hide();
debugstr("Flash 10.0.0+ is required but you are running Flash " + args.flashVersion.replace(/,/g, "."));
});

clip.on('complete', function (client, args) {
debugstr("Copied text to clipboard: " + args.text);
});

// jquery stuff (optional)
function debugstr(text) {
$("#d_debug").append($("<p>").text(text));
}
});
</script>
</body>
</html>


代码说明:

1. 要在服务器环境下测试才有效,静态网页时是没有反应的。

2. html中需要导入文件:

  


3. 实例文件下载:Demo

4. 使用中下载源码后根据需要修改即可。

欢迎转载,转载请注明出处:/article/6325277.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: