zoukankan      html  css  js  c++  java
  • Easy Multiple Copy to Clipboard by ZeroClipboard

    要实现在多个复制按钮复制的功能(具体代码在附件中,路径修改一下就行了):

     

     

    Html代码 复制代码 收藏代码
    1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
    2. <%   
    3. String path = request.getContextPath();   
    4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";   
    5. %>  
    6.   
    7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
    8. <html>  
    9.   <head>  
    10.     <base href="<%=basePath%>">  
    11.        
    12.     <title>My JSP 'clip.jsp' starting page</title>  
    13.        
    14.     <meta http-equiv="pragma" content="no-cache">  
    15.     <meta http-equiv="cache-control" content="no-cache">  
    16.     <meta http-equiv="expires" content="0">       
    17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    18.     <meta http-equiv="description" content="This is my page">  
    19.     <style type="text/css">  
    20.         .clip_button {   
    21.             background: #ddd;   
    22.             padding: 4px;   
    23.              50px;   
    24.         }   
    25.     </style>  
    26.     <script src="<%=request.getContextPath()%>/page/jquery-1.4.2.min.js"></script>  
    27.     <script src="<%=request.getContextPath()%>/common/ZeroClipboard/ZeroClipboard.js"></script>  
    28.     <script>  
    29.         var clip = null;//ZeroClipboard.Client对象   
    30.         var current_id = null;//当前所在的文本元素id   
    31.         //指定ZeroClipboard.swf位置   
    32.         ZeroClipboard.setMoviePath("<%=basePath%>common/ZeroClipboard/ZeroClipboard.swf");     
    33.         $(function(){   
    34.             clip = new ZeroClipboard.Client();//创建ZeroClipboard.Client对象   
    35.             clip.setHandCursor(true);//鼠标移动到元素上之后显示手型   
    36.             clip.glue('textid');   
    37.             //添加复制成功之后的操作   
    38.             clip.addEventListener('complete', function() {   
    39.                 alert('复制成功,内容为:'+clip.clipText);   
    40.             });   
    41.             //添加mouseover事件,当鼠标移到该元素上面的时候,将flash div 也移到到该元素位置   
    42.             $("div.clip_button").each(function(){   
    43.                 $(this).bind('mouseover',function(){   
    44.                     var button_id = $(this).attr('id');//复制div的id   
    45.                     var text_id = button_id+'_text';//要复制的元素id   
    46.                     move_swf(text_id , button_id);   
    47.                 });   
    48.             });   
    49.         });   
    50.         //移动浮动flash div到指定的地方,从而只需要使用一个flash即可在多个地方实现复制功能   
    51.         function move_swf(text_id,button_id) {   
    52.             //重新指定flash浮动div位置,用reposition   
    53.             clip.reposition(button_id);   
    54.             clip.setText($('#'+text_id).val());   
    55.         }   
    56.     </script>  
    57.   </head>  
    58.      
    59.   <body>  
    60.         <table width="0" border="0">  
    61.             <tr>  
    62.                 <td>  
    63.                     <input type='text' id='textid_text' value='第一个输入框' />  
    64.                 </td>  
    65.                 <td>  
    66.                     <div id='textid' class='clip_button'>  
    67.                         复 制   
    68.                     </div>  
    69.                 </td>  
    70.             </tr>  
    71.             <tr>  
    72.                 <td>  
    73.                     <input type='text' id='textid2_text' value='第二个输入框' />  
    74.                 </td>  
    75.                 <td>  
    76.                     <div id='textid2' class='clip_button'>  
    77.                         复 制   
    78.                     </div>  
    79.                 </td>  
    80.             </tr>  
    81.             <tr>  
    82.                 <td>  
    83.                     <input type='text' id='textid3_text' value='第三个输入框' />  
    84.                 </td>  
    85.                 <td>  
    86.                     <div id='textid3' class='clip_button'>  
    87.                         复 制   
    88.                     </div>  
    89.                 </td>  
    90.             </tr>  
    91.             <tr>  
    92.                 <td>  
    93.                     <input type='text' id='textid4_text' value='第四个输入框' />  
    94.                 </td>  
    95.                 <td>  
    96.                     <div id='textid4' class='clip_button'>  
    97.                         复 制   
    98.                     </div>  
    99.                 </td>  
    100.             </tr>  
    101.             <tr>  
    102.                 <td>  
    103.                     <input type='text' id='textid5_text' value='第五个输入框' />  
    104.                 </td>  
    105.                 <td>  
    106.                     <div id='textid5' class='clip_button'>  
    107.                         复 制   
    108.                     </div>  
    109.                 </td>  
    110.             </tr>  
    111.         </table>  
    112.     </body>  
    113. </html>  
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'clip.jsp' starting page</title>
        
    	<meta http-equiv="pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    	<meta http-equiv="description" content="This is my page">
    	<style type="text/css">
    		.clip_button {
    			background: #ddd;
    			padding: 4px;
    			 50px;
    		}
    	</style>
    	<script src="<%=request.getContextPath()%>/page/jquery-1.4.2.min.js"></script>
    	<script src="<%=request.getContextPath()%>/common/ZeroClipboard/ZeroClipboard.js"></script>
    	<script>
    		var clip = null;//ZeroClipboard.Client对象
    		var current_id = null;//当前所在的文本元素id
    		//指定ZeroClipboard.swf位置
    		ZeroClipboard.setMoviePath("<%=basePath%>common/ZeroClipboard/ZeroClipboard.swf");  
    		$(function(){
    			clip = new ZeroClipboard.Client();//创建ZeroClipboard.Client对象
    			clip.setHandCursor(true);//鼠标移动到元素上之后显示手型
    			clip.glue('textid');
    			//添加复制成功之后的操作
    			clip.addEventListener('complete', function() {
    				alert('复制成功,内容为:'+clip.clipText);
    			});
    			//添加mouseover事件,当鼠标移到该元素上面的时候,将flash div 也移到到该元素位置
    			$("div.clip_button").each(function(){
    				$(this).bind('mouseover',function(){
    					var button_id = $(this).attr('id');//复制div的id
    					var text_id = button_id+'_text';//要复制的元素id
    					move_swf(text_id , button_id);
    				});
    			});
    		});
    		//移动浮动flash div到指定的地方,从而只需要使用一个flash即可在多个地方实现复制功能
    		function move_swf(text_id,button_id) {
    			//重新指定flash浮动div位置,用reposition
    			clip.reposition(button_id);
    			clip.setText($('#'+text_id).val());
    		}
    	</script>
      </head>
      
      <body>
    		<table width="0" border="0">
    			<tr>
    				<td>
    					<input type='text' id='textid_text' value='第一个输入框' />
    				</td>
    				<td>
    					<div id='textid' class='clip_button'>
    						复 制
    					</div>
    				</td>
    			</tr>
    			<tr>
    				<td>
    					<input type='text' id='textid2_text' value='第二个输入框' />
    				</td>
    				<td>
    					<div id='textid2' class='clip_button'>
    						复 制
    					</div>
    				</td>
    			</tr>
    			<tr>
    				<td>
    					<input type='text' id='textid3_text' value='第三个输入框' />
    				</td>
    				<td>
    					<div id='textid3' class='clip_button'>
    						复 制
    					</div>
    				</td>
    			</tr>
    			<tr>
    				<td>
    					<input type='text' id='textid4_text' value='第四个输入框' />
    				</td>
    				<td>
    					<div id='textid4' class='clip_button'>
    						复 制
    					</div>
    				</td>
    			</tr>
    			<tr>
    				<td>
    					<input type='text' id='textid5_text' value='第五个输入框' />
    				</td>
    				<td>
    					<div id='textid5' class='clip_button'>
    						复 制
    					</div>
    				</td>
    			</tr>
    		</table>
    	</body>
    </html>
    
    

     

    ZeroClipboard.js源码:

    Js代码 复制代码 收藏代码
    1. // Simple Set Clipboard System   
    2. // Author: Joseph Huckaby   
    3.   
    4. var ZeroClipboard = {   
    5.        
    6.     version: "1.0.7",   
    7.     clients: {}, // registered upload clients on page, indexed by id   
    8.     moviePath: 'ZeroClipboard.swf'// URL to movie   
    9.     nextId: 1, // ID of next movie   
    10.        
    11.     $: function(thingy) {   
    12.         // simple DOM lookup utility function   
    13.         if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);   
    14.         if (!thingy.addClass) {   
    15.             // extend element with a few useful methods   
    16.             thingy.hide = function() { this.style.display = 'none'; };   
    17.             thingy.show = function() { this.style.display = ''; };   
    18.             thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; };   
    19.             thingy.removeClass = function(name) {   
    20.                 var classes = this.className.split(/s+/);   
    21.                 var idx = -1;   
    22.                 for (var k = 0; k < classes.length; k++) {   
    23.                     if (classes[k] == name) { idx = k; k = classes.length; }   
    24.                 }   
    25.                 if (idx > -1) {   
    26.                     classes.splice( idx, 1 );   
    27.                     this.className = classes.join(' ');   
    28.                 }   
    29.                 return this;   
    30.             };   
    31.             thingy.hasClass = function(name) {   
    32.                 return !!this.className.match( new RegExp("\s*" + name + "\s*") );   
    33.             };   
    34.         }   
    35.         return thingy;   
    36.     },   
    37.        
    38.     setMoviePath: function(path) {   
    39.         // set path to ZeroClipboard.swf   
    40.         this.moviePath = path;   
    41.     },   
    42.        
    43.     dispatch: function(id, eventName, args) {   
    44.         // receive event from flash movie, send to client          
    45.         var client = this.clients[id];   
    46.         if (client) {   
    47.             client.receiveEvent(eventName, args);   
    48.         }   
    49.     },   
    50.        
    51.     register: function(id, client) {   
    52.         // register new client to receive events   
    53.         this.clients[id] = client;   
    54.     },   
    55.        
    56.     getDOMObjectPosition: function(obj, stopObj) {   
    57.         // get absolute coordinates for dom element   
    58.         var info = {   
    59.             left: 0,    
    60.             top: 0,    
    61.              obj.width ? obj.width : obj.offsetWidth,    
    62.             height: obj.height ? obj.height : obj.offsetHeight   
    63.         };   
    64.   
    65.         while (obj && (obj != stopObj)) {   
    66.             info.left += obj.offsetLeft;   
    67.             info.top += obj.offsetTop;   
    68.             obj = obj.offsetParent;   
    69.         }   
    70.   
    71.         return info;   
    72.     },   
    73.        
    74.     Client: function(elem) {   
    75.         // constructor for new simple upload client   
    76.         this.handlers = {};   
    77.            
    78.         // unique ID   
    79.         this.id = ZeroClipboard.nextId++;   
    80.         this.movieId = 'ZeroClipboardMovie_' + this.id;   
    81.            
    82.         // register client with singleton to receive flash events   
    83.         ZeroClipboard.register(this.id, this);   
    84.            
    85.         // create movie   
    86.         if (elem) this.glue(elem);   
    87.     }   
    88. };   
    89.   
    90. ZeroClipboard.Client.prototype = {   
    91.        
    92.     id: 0, // unique ID for us   
    93.     ready: false// whether movie is ready to receive events or not   
    94.     movie: null// reference to movie object   
    95.     clipText: ''// text to copy to clipboard   
    96.     handCursorEnabled: true// whether to show hand cursor, or default pointer cursor   
    97.     cssEffects: true// enable CSS mouse effects on dom container   
    98.     handlers: null// user event handlers   
    99.        
    100.     glue: function(elem, appendElem, stylesToAdd) {   
    101.         // glue to DOM element   
    102.         // elem can be ID or actual DOM element object   
    103.         this.domElement = ZeroClipboard.$(elem);   
    104.            
    105.         // float just above object, or zIndex 99 if dom element isn't set   
    106.         var zIndex = 99;   
    107.         if (this.domElement.style.zIndex) {   
    108.             zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;   
    109.         }   
    110.            
    111.         if (typeof(appendElem) == 'string') {   
    112.             appendElem = ZeroClipboard.$(appendElem);   
    113.         }   
    114.         else if (typeof(appendElem) == 'undefined') {   
    115.             appendElem = document.getElementsByTagName('body')[0];   
    116.         }   
    117.            
    118.         // find X/Y position of domElement   
    119.         var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem);   
    120.            
    121.         // create floating DIV above element   
    122.         this.div = document.createElement('div');   
    123.         var style = this.div.style;   
    124.         style.position = 'absolute';   
    125.         style.left = '' + box.left + 'px';   
    126.         style.top = '' + box.top + 'px';   
    127.         style.width = '' + box.width + 'px';   
    128.         style.height = '' + box.height + 'px';   
    129.         style.zIndex = zIndex;   
    130.            
    131.         if (typeof(stylesToAdd) == 'object') {   
    132.             for (addedStyle in stylesToAdd) {   
    133.                 style[addedStyle] = stylesToAdd[addedStyle];   
    134.             }   
    135.         }   
    136.            
    137.         // style.backgroundColor = '#f00'; // debug   
    138.            
    139.         appendElem.appendChild(this.div);   
    140.            
    141.         this.div.innerHTML = this.getHTML( box.width, box.height );   
    142.     },   
    143.        
    144.     getHTML: function(width, height) {   
    145.         // return HTML for movie   
    146.         var html = '';   
    147.         var flashvars = 'id=' + this.id +    
    148.             '&width=' + width +    
    149.             '&height=' + height;   
    150.                
    151.         if (navigator.userAgent.match(/MSIE/)) {   
    152.             // IE gets an OBJECT tag   
    153.             var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';   
    154.             html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';   
    155.         }   
    156.         else {   
    157.             // all other browsers get an EMBED tag   
    158.             html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';   
    159.         }   
    160.         return html;   
    161.     },   
    162.        
    163.     hide: function() {   
    164.         // temporarily hide floater offscreen   
    165.         if (this.div) {   
    166.             this.div.style.left = '-2000px';   
    167.         }   
    168.     },   
    169.        
    170.     show: function() {   
    171.         // show ourselves after a call to hide()   
    172.         this.reposition();   
    173.     },   
    174.        
    175.     destroy: function() {   
    176.         // destroy control and floater   
    177.         if (this.domElement && this.div) {   
    178.             this.hide();   
    179.             this.div.innerHTML = '';   
    180.                
    181.             var body = document.getElementsByTagName('body')[0];   
    182.             try { body.removeChild( this.div ); } catch(e) {;}   
    183.                
    184.             this.domElement = null;   
    185.             this.div = null;   
    186.         }   
    187.     },   
    188.        
    189.     reposition: function(elem) {   
    190.         // reposition our floating div, optionally to new container   
    191.         // warning: container CANNOT change size, only position   
    192.         if (elem) {   
    193.             this.domElement = ZeroClipboard.$(elem);   
    194.             if (!this.domElement) this.hide();   
    195.         }   
    196.            
    197.         if (this.domElement && this.div) {   
    198.             var box = ZeroClipboard.getDOMObjectPosition(this.domElement);   
    199.             var style = this.div.style;   
    200.             style.left = '' + box.left + 'px';   
    201.             style.top = '' + box.top + 'px';   
    202.         }   
    203.     },   
    204.        
    205.     setText: function(newText) {   
    206.         // set text to be copied to clipboard   
    207.         this.clipText = newText;   
    208.         if (this.ready) this.movie.setText(newText);   
    209.     },   
    210.        
    211.     addEventListener: function(eventName, func) {   
    212.         // add user event listener for event   
    213.         // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel   
    214.         eventName = eventName.toString().toLowerCase().replace(/^on/, '');   
    215.         if (!this.handlers[eventName]) this.handlers[eventName] = [];   
    216.         this.handlers[eventName].push(func);   
    217.     },   
    218.        
    219.     setHandCursor: function(enabled) {   
    220.         // enable hand cursor (true), or default arrow cursor (false)   
    221.         this.handCursorEnabled = enabled;   
    222.         if (this.ready) this.movie.setHandCursor(enabled);   
    223.     },   
    224.        
    225.     setCSSEffects: function(enabled) {   
    226.         // enable or disable CSS effects on DOM container   
    227.         this.cssEffects = !!enabled;   
    228.     },   
    229.        
    230.     receiveEvent: function(eventName, args) {   
    231.         // receive event from flash   
    232.         eventName = eventName.toString().toLowerCase().replace(/^on/, '');   
    233.                    
    234.         // special behavior for certain events   
    235.         switch (eventName) {   
    236.             case 'load':   
    237.                 // movie claims it is ready, but in IE this isn't always the case...   
    238.                 // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function   
    239.                 this.movie = document.getElementById(this.movieId);   
    240.                 if (!this.movie) {   
    241.                     var self = this;   
    242.                     setTimeout( function() { self.receiveEvent('load'null); }, 1 );   
    243.                     return;   
    244.                 }   
    245.                    
    246.                 // firefox on pc needs a "kick" in order to set these in certain cases   
    247.                 if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {   
    248.                     var self = this;   
    249.                     setTimeout( function() { self.receiveEvent('load'null); }, 100 );   
    250.                     this.ready = true;   
    251.                     return;   
    252.                 }   
    253.                    
    254.                 this.ready = true;   
    255.                 this.movie.setText( this.clipText );   
    256.                 this.movie.setHandCursor( this.handCursorEnabled );   
    257.                 break;   
    258.                
    259.             case 'mouseover':   
    260.                 if (this.domElement && this.cssEffects) {   
    261.                     this.domElement.addClass('hover');   
    262.                     if (this.recoverActive) this.domElement.addClass('active');   
    263.                 }   
    264.                 break;   
    265.                
    266.             case 'mouseout':   
    267.                 if (this.domElement && this.cssEffects) {   
    268.                     this.recoverActive = false;   
    269.                     if (this.domElement.hasClass('active')) {   
    270.                         this.domElement.removeClass('active');   
    271.                         this.recoverActive = true;   
    272.                     }   
    273.                     this.domElement.removeClass('hover');   
    274.                 }   
    275.                 break;   
    276.                
    277.             case 'mousedown':   
    278.                 if (this.domElement && this.cssEffects) {   
    279.                     this.domElement.addClass('active');   
    280.                 }   
    281.                 break;   
    282.                
    283.             case 'mouseup':   
    284.                 if (this.domElement && this.cssEffects) {   
    285.                     this.domElement.removeClass('active');   
    286.                     this.recoverActive = false;   
    287.                 }   
    288.                 break;   
    289.         } // switch eventName   
    290.            
    291.         if (this.handlers[eventName]) {   
    292.             for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {   
    293.                 var func = this.handlers[eventName][idx];   
    294.                
    295.                 if (typeof(func) == 'function') {   
    296.                     // actual function reference   
    297.                     func(this, args);   
    298.                 }   
    299.                 else if ((typeof(func) == 'object') && (func.length == 2)) {   
    300.                     // PHP style object + method, i.e. [myObject, 'myMethod']   
    301.                     func[0][ func[1] ](this, args);   
    302.                 }   
    303.                 else if (typeof(func) == 'string') {   
    304.                     // name of function   
    305.                     window[func](this, args);   
    306.                 }   
    307.             } // foreach event handler defined   
    308.         } // user defined handler for event   
    309.     }   
    310.        
    311. };  
    // Simple Set Clipboard System
    // Author: Joseph Huckaby
    
    var ZeroClipboard = {
    	
    	version: "1.0.7",
    	clients: {}, // registered upload clients on page, indexed by id
    	moviePath: 'ZeroClipboard.swf', // URL to movie
    	nextId: 1, // ID of next movie
    	
    	$: function(thingy) {
    		// simple DOM lookup utility function
    		if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
    		if (!thingy.addClass) {
    			// extend element with a few useful methods
    			thingy.hide = function() { this.style.display = 'none'; };
    			thingy.show = function() { this.style.display = ''; };
    			thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; };
    			thingy.removeClass = function(name) {
    				var classes = this.className.split(/s+/);
    				var idx = -1;
    				for (var k = 0; k < classes.length; k++) {
    					if (classes[k] == name) { idx = k; k = classes.length; }
    				}
    				if (idx > -1) {
    					classes.splice( idx, 1 );
    					this.className = classes.join(' ');
    				}
    				return this;
    			};
    			thingy.hasClass = function(name) {
    				return !!this.className.match( new RegExp("\s*" + name + "\s*") );
    			};
    		}
    		return thingy;
    	},
    	
    	setMoviePath: function(path) {
    		// set path to ZeroClipboard.swf
    		this.moviePath = path;
    	},
    	
    	dispatch: function(id, eventName, args) {
    		// receive event from flash movie, send to client		
    		var client = this.clients[id];
    		if (client) {
    			client.receiveEvent(eventName, args);
    		}
    	},
    	
    	register: function(id, client) {
    		// register new client to receive events
    		this.clients[id] = client;
    	},
    	
    	getDOMObjectPosition: function(obj, stopObj) {
    		// get absolute coordinates for dom element
    		var info = {
    			left: 0, 
    			top: 0, 
    			 obj.width ? obj.width : obj.offsetWidth, 
    			height: obj.height ? obj.height : obj.offsetHeight
    		};
    
    		while (obj && (obj != stopObj)) {
    			info.left += obj.offsetLeft;
    			info.top += obj.offsetTop;
    			obj = obj.offsetParent;
    		}
    
    		return info;
    	},
    	
    	Client: function(elem) {
    		// constructor for new simple upload client
    		this.handlers = {};
    		
    		// unique ID
    		this.id = ZeroClipboard.nextId++;
    		this.movieId = 'ZeroClipboardMovie_' + this.id;
    		
    		// register client with singleton to receive flash events
    		ZeroClipboard.register(this.id, this);
    		
    		// create movie
    		if (elem) this.glue(elem);
    	}
    };
    
    ZeroClipboard.Client.prototype = {
    	
    	id: 0, // unique ID for us
    	ready: false, // whether movie is ready to receive events or not
    	movie: null, // reference to movie object
    	clipText: '', // text to copy to clipboard
    	handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
    	cssEffects: true, // enable CSS mouse effects on dom container
    	handlers: null, // user event handlers
    	
    	glue: function(elem, appendElem, stylesToAdd) {
    		// glue to DOM element
    		// elem can be ID or actual DOM element object
    		this.domElement = ZeroClipboard.$(elem);
    		
    		// float just above object, or zIndex 99 if dom element isn't set
    		var zIndex = 99;
    		if (this.domElement.style.zIndex) {
    			zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
    		}
    		
    		if (typeof(appendElem) == 'string') {
    			appendElem = ZeroClipboard.$(appendElem);
    		}
    		else if (typeof(appendElem) == 'undefined') {
    			appendElem = document.getElementsByTagName('body')[0];
    		}
    		
    		// find X/Y position of domElement
    		var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem);
    		
    		// create floating DIV above element
    		this.div = document.createElement('div');
    		var style = this.div.style;
    		style.position = 'absolute';
    		style.left = '' + box.left + 'px';
    		style.top = '' + box.top + 'px';
    		style.width = '' + box.width + 'px';
    		style.height = '' + box.height + 'px';
    		style.zIndex = zIndex;
    		
    		if (typeof(stylesToAdd) == 'object') {
    			for (addedStyle in stylesToAdd) {
    				style[addedStyle] = stylesToAdd[addedStyle];
    			}
    		}
    		
    		// style.backgroundColor = '#f00'; // debug
    		
    		appendElem.appendChild(this.div);
    		
    		this.div.innerHTML = this.getHTML( box.width, box.height );
    	},
    	
    	getHTML: function(width, height) {
    		// return HTML for movie
    		var html = '';
    		var flashvars = 'id=' + this.id + 
    			'&width=' + width + 
    			'&height=' + height;
    			
    		if (navigator.userAgent.match(/MSIE/)) {
    			// IE gets an OBJECT tag
    			var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
    			html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';
    		}
    		else {
    			// all other browsers get an EMBED tag
    			html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';
    		}
    		return html;
    	},
    	
    	hide: function() {
    		// temporarily hide floater offscreen
    		if (this.div) {
    			this.div.style.left = '-2000px';
    		}
    	},
    	
    	show: function() {
    		// show ourselves after a call to hide()
    		this.reposition();
    	},
    	
    	destroy: function() {
    		// destroy control and floater
    		if (this.domElement && this.div) {
    			this.hide();
    			this.div.innerHTML = '';
    			
    			var body = document.getElementsByTagName('body')[0];
    			try { body.removeChild( this.div ); } catch(e) {;}
    			
    			this.domElement = null;
    			this.div = null;
    		}
    	},
    	
    	reposition: function(elem) {
    		// reposition our floating div, optionally to new container
    		// warning: container CANNOT change size, only position
    		if (elem) {
    			this.domElement = ZeroClipboard.$(elem);
    			if (!this.domElement) this.hide();
    		}
    		
    		if (this.domElement && this.div) {
    			var box = ZeroClipboard.getDOMObjectPosition(this.domElement);
    			var style = this.div.style;
    			style.left = '' + box.left + 'px';
    			style.top = '' + box.top + 'px';
    		}
    	},
    	
    	setText: function(newText) {
    		// set text to be copied to clipboard
    		this.clipText = newText;
    		if (this.ready) this.movie.setText(newText);
    	},
    	
    	addEventListener: function(eventName, func) {
    		// add user event listener for event
    		// event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
    		eventName = eventName.toString().toLowerCase().replace(/^on/, '');
    		if (!this.handlers[eventName]) this.handlers[eventName] = [];
    		this.handlers[eventName].push(func);
    	},
    	
    	setHandCursor: function(enabled) {
    		// enable hand cursor (true), or default arrow cursor (false)
    		this.handCursorEnabled = enabled;
    		if (this.ready) this.movie.setHandCursor(enabled);
    	},
    	
    	setCSSEffects: function(enabled) {
    		// enable or disable CSS effects on DOM container
    		this.cssEffects = !!enabled;
    	},
    	
    	receiveEvent: function(eventName, args) {
    		// receive event from flash
    		eventName = eventName.toString().toLowerCase().replace(/^on/, '');
    				
    		// special behavior for certain events
    		switch (eventName) {
    			case 'load':
    				// movie claims it is ready, but in IE this isn't always the case...
    				// bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
    				this.movie = document.getElementById(this.movieId);
    				if (!this.movie) {
    					var self = this;
    					setTimeout( function() { self.receiveEvent('load', null); }, 1 );
    					return;
    				}
    				
    				// firefox on pc needs a "kick" in order to set these in certain cases
    				if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
    					var self = this;
    					setTimeout( function() { self.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;
    		} // switch eventName
    		
    		if (this.handlers[eventName]) {
    			for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
    				var func = this.handlers[eventName][idx];
    			
    				if (typeof(func) == 'function') {
    					// actual function reference
    					func(this, args);
    				}
    				else if ((typeof(func) == 'object') && (func.length == 2)) {
    					// PHP style object + method, i.e. [myObject, 'myMethod']
    					func[0][ func[1] ](this, args);
    				}
    				else if (typeof(func) == 'string') {
    					// name of function
    					window[func](this, args);
    				}
    			} // foreach event handler defined
    		} // user defined handler for event
    	}
    	
    };
    

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------我是分割线------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

     

     

     

     

     

     

     

     

    zeroclipboard官网:https://github.com/zeroclipboard/ZeroClipboard

     

    下载压缩包,得到两个“ZeroClipboard.js”和“ZeroClipboard.swf”两个文件。

    首先页面中载入ZeroClipboard.js

     

    ZeroClipboard.setMoviePath( “ZeroClipboard.swf路径” );来指定ZeroClipboard.swf的地址。

     

    demo:

     

     

    Js代码 复制代码 收藏代码
    1. <!DOCTYPE html>   
    2. <html>   
    3. <head>   
    4. <meta charset="utf-8" />   
    5. <title>ZeroClipboard demo实例</title>   
    6.     <script src="../js/ZeroClipboard.js"></script>   
    7.     <script src="../js/jquery.min.js"></script>   
    8.     <script>   
    9.         $(function(){   
    10.             var clip = new ZeroClipboard( document.getElementById("copy-button"), {   
    11.                           //指定ZeroClipboard.swf的路径   
    12.               moviePath: "../js/ZeroClipboard.swf"    
    13.             } );   
    14.                
    15.             clip.on( 'load'function(client) {   
    16.               // alert( "movie is loaded" );   
    17.             } );   
    18.                
    19.             clip.on( 'complete'function(client, args) {   
    20.               //this.style.display = 'none'; // "this" is the element that was clicked   
    21.               alert("复制成功,复制的内容为: " + args.text );   
    22.             } );   
    23.                
    24.             clip.on( 'mouseover'function(client) {   
    25.               // alert("mouse over");   
    26.             } );   
    27.                
    28.             clip.on( 'mouseout'function(client) {   
    29.               // alert("mouse out");   
    30.             } );   
    31.                
    32.             clip.on( 'mousedown'function(client) {   
    33.                 //在这里为剪贴板赋值   
    34.                 clip.setText($("#_input").val());   
    35.             } );   
    36.                
    37.             clip.on( 'mouseup'function(client) {   
    38.               // alert("mouse up");   
    39.             } );   
    40.         });   
    41.     </script>   
    42. </head>   
    43. <body>   
    44.  <button id="copy-button" title="复制到剪贴板">复制到剪贴板</button>   
    45.  <input type="text" id="_input">   
    46. </body>   
    47. </html>  
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>ZeroClipboard demo实例</title>
    	<script src="../js/ZeroClipboard.js"></script>
    	<script src="../js/jquery.min.js"></script>
        <script>
    		$(function(){
    			var clip = new ZeroClipboard( document.getElementById("copy-button"), {
                              //指定ZeroClipboard.swf的路径
    			  moviePath: "../js/ZeroClipboard.swf" 
    			} );
    			
    			clip.on( 'load', function(client) {
    			  // alert( "movie is loaded" );
    			} );
    			
    			clip.on( 'complete', function(client, args) {
    			  //this.style.display = 'none'; // "this" is the element that was clicked
    			  alert("复制成功,复制的内容为: " + args.text );
    			} );
    			
    			clip.on( 'mouseover', function(client) {
    			  // alert("mouse over");
    			} );
    			
    			clip.on( 'mouseout', function(client) {
    			  // alert("mouse out");
    			} );
    			
    			clip.on( 'mousedown', function(client) {
    				//在这里为剪贴板赋值
    				clip.setText($("#_input").val());
    			} );
    			
    			clip.on( 'mouseup', function(client) {
    			  // alert("mouse up");
    			} );
    		});
        </script>
    </head>
    <body>
     <button id="copy-button" title="复制到剪贴板">复制到剪贴板</button>
     <input type="text" id="_input">
    </body>
    </html>

     

    不过在IE8下面好像有点问题,试了一下官网的例子,同样有问题,估计后面的版本会修复

  • 相关阅读:
    算法70----只有两个键的键盘【动态规划】
    Shell
    Shell
    Shell
    Shell
    Shell
    Tools
    Jenkins
    Java
    Product
  • 原文地址:https://www.cnblogs.com/wangluochong/p/3631175.html
Copyright © 2011-2022 走看看