最近接了个项目,其中有项目需求是这样的,需要复制内容到剪切板,因为有众多浏览器,所以兼容性很重要,下面通过本文给大家介绍 Javascript 复制实例详解,对 js 复制相关知识感兴趣的朋友一起学习吧
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
在做项目时有一个需求,是需要复制内容到剪切板,因为有众多浏览器,所以要兼容性很重要。
1、最简单的 copy,只能在 IE 下使用
使用 clipboardData 方法
- <script type="text/javascript">
- function copy(){
- window.clipboardData.setData("text",document.getElementById("name").value);
- alert("The text is on the clipboard, try to paste it!");
- }
- </script>
2、跨浏览器的,但是 Firefox 无法复制
- <head>
- <script type="text/javascript">
- function CopyToClipboard () {
- var input = document.getElementById ("toClipboard");
- var textToClipboard = input.value;
- var success = true;
- if (window.clipboardData) { // Internet Explorer
- window.clipboardData.setData ("Text", textToClipboard);
- }
- else {
- // create a temporary element for the execCommand method
- var forExecElement = CreateElementForExecCommand (textToClipboard);
- /* Select the contents of the element
- (the execCommand for 'copy' method works on the selection) */
- SelectContent (forExecElement);
- var supported = true;
- // UniversalXPConnect privilege is required for clipboard access in Firefox
- try {
- if (window.netscape && netscape.security) {
- netscape.security.PrivilegeManager.enablePrivilege ("UniversalXPConnect");
- }
- // Copy the selected content to the clipboard
- // Works in Firefox and in Safari before version 5
- success = document.execCommand ("copy", false, null);
- }
- catch (e) {
- success = false;
- }
- // remove the temporary element
- document.body.removeChild (forExecElement);
- }
- if (success) {
- alert ("The text is on the clipboard, try to paste it!");
- }
- else {
- alert ("Your browser doesn't allow clipboard access!");
- }
- }
- function CreateElementForExecCommand (textToClipboard) {
- var forExecElement = document.createElement ("div");
- // place outside the visible area
- forExecElement.style.position = "absolute";
- forExecElement.style.left = "-10000px";
- forExecElement.style.top = "-10000px";
- // write the necessary text into the element and append to the document
- forExecElement.textContent = textToClipboard;
- document.body.appendChild (forExecElement);
- // the contentEditable mode is necessary for the execCommand method in Firefox
- forExecElement.contentEditable = true;
- return forExecElement;
- }
- function SelectContent (element) {
- // first create a range
- var rangeToSelect = document.createRange ();
- rangeToSelect.selectNodeContents (element);
- // select the contents
- var selection = window.getSelection ();
- selection.removeAllRanges ();
- selection.addRange (rangeToSelect);
- }
- </script>
- </head>
- <body>
- <input id="toClipboard" value="text to clipboard"/>
- <button onclick='CopyToClipboard ()'>Copy text to clipboard</button>
- </body>
测试后,Firefox 访问失败
3、万能的 flash
不要重复造轮子了,有一个使用广泛的类库 ZeroClipboard
Zero Clipboard 的实现原理
Zero Clipboard 利用 Flash 进行复制,之前有 Clipboard Copy 解决方案,其利用的是一个隐藏的 Flash。但最新的 Flash Player 10 只允许在 Flash 上进行操作才能启动剪贴板。所以 Zero Clipboard 对此进行了改进,用了一个透明的 Flash ,让其漂浮在按钮之上,这样其实点击的不是按钮而是 Flash ,也就可以使用 Flash 的复制功能了。
创建一个透明的 flash
将这个 flash 浮在按钮上层
确定要复制的文本是什么
监听这个透明 flash 的鼠标点击事件
该 flash 被点击之后,完成剪切板处理
对于这几件事,ZeroClipboard 分别提供了不同的 api,来完成整个需求
如何使用 Zero Clipboard
git clone https://github.com/chenpingzhao/easycopy.git
关于 ZeroClipboard.js
可以改成下面的 ":hover" 改成 ".hover"
- copy - botton.hover {
- border - color: #FF6633;
- }
我们可以调用 clip.setCSSEffects(true); 这样 Zero Clipboard 会自动为我们处理:将类 .hover 当成伪类 :hover*/
- setCSSEffects: function(A) {
- this.cssEffects = !!A
- },
- /*Zero Clipboard 提供了一些事件,你可以自定义函数处理这些事件。
- Zero Clipboard 事件处理函数为 addEventListener(); 例如当 Flash 完全载入后会触发一个事件 "load"
- clip.addEventListener( "load", function(client) {
- alert("Flash 加载完毕!");
- });*/
- receiveEvent: function(D, E) {
- D = D.toString().toLowerCase().replace(/^on/, "");
- switch (D) {
- case "load":
- this.movie = document.getElementById(this.movieId);
- if (!this.movie) {
- var C = this;
- setTimeout(function() {
- C.receiveEvent("load", null)
- },
- 1);
- return
- }
- if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
- var C = this;
- setTimeout(function() {
- C.receiveEvent("load", null)
- },
- 100);
- this.ready = true;
- return
- }
- this.ready = true;
- this.movie.setText(this.clipText);
- this.movie.setHandCursor(this.handCursorEnabled);
- break;
- case "mouseover":
- if (this.domElement && this.cssEffects) {
- this.domElement.addClass("hover");
- if (this.recoverActive) {
- this.domElement.addClass("active")
- }
- }
- break;
- case "mouseout":
- if (this.domElement && this.cssEffects) {
- this.recoverActive = false;
- if (this.domElement.hasClass("active")) {
- this.domElement.removeClass("active");
- this.recoverActive = true
- }
- this.domElement.removeClass("hover")
- }
- break;
- case "mousedown":
- if (this.domElement && this.cssEffects) {
- this.domElement.addClass("active")
- }
- break;
- case "mouseup":
- if (this.domElement && this.cssEffects) {
- this.domElement.removeClass("active");
- this.recoverActive = false
- }
- break
- }
- if (this.handlers[D]) {
- for (var B = 0,
- A = this.handlers[D].length; B < A; B++) {
- var F = this.handlers[D][B];
- if (typeof(F) == "function") {
- F(this, E)
- } else {
- if ((typeof(F) == "object") && (F.length == 2)) {
- F[0][F[1]](this, E)
- } else {
- if (typeof(F) == "string") {
- window[F](this, E)
- }
- }
- }
- }
- }
- }
- };
来源: http://www.phperz.com/article/17/0218/267305.html