http://my.oschina.net/xshuai/blog/411399
ZeroClipboard实现多个浏览器兼容的复制文本到剪贴板的功能
本人在项目中使用的js版本。为了方便大家下载。直接粘贴代码给大家看。版本是1.2.0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | /*! * ZeroClipboard * The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface. * Copyright (c) 2013 Jon Rohan, James M. Greene * Licensed MIT * http://zeroclipboard.org/ * v1.2.0-beta.4 */ ( function () { "use strict" ; var _camelizeCssPropName = function () { var matcherRegex = /\-([a-z])/g, replacerFn = function (match, group) { return group.toUpperCase(); }; return function (prop) { return prop.replace(matcherRegex, replacerFn); }; }(); var _getStyle = function (el, prop) { var value, camelProp, tagName, possiblePointers, i, len; if (window.getComputedStyle) { value = window.getComputedStyle(el, null ).getPropertyValue(prop); } else { camelProp = _camelizeCssPropName(prop); if (el.currentStyle) { value = el.currentStyle[camelProp]; } else { value = el.style[camelProp]; } } if (prop === "cursor" ) { if (!value || value === "auto" ) { tagName = el.tagName.toLowerCase(); possiblePointers = [ "a" ]; for (i = 0, len = possiblePointers.length; i < len; i++) { if (tagName === possiblePointers[i]) { return "pointer" ; } } } } return value; }; var _elementMouseOver = function (event) { if (!ZeroClipboard.prototype._singleton) return ; if (!event) { event = window.event; } var target; if ( this !== window) { target = this ; } else if (event.target) { target = event.target; } else if (event.srcElement) { target = event.srcElement; } ZeroClipboard.prototype._singleton.setCurrent(target); }; var _addEventHandler = function (element, method, func) { if (element.addEventListener) { element.addEventListener(method, func, false ); } else if (element.attachEvent) { element.attachEvent( "on" + method, func); } }; var _removeEventHandler = function (element, method, func) { if (element.removeEventListener) { element.removeEventListener(method, func, false ); } else if (element.detachEvent) { element.detachEvent( "on" + method, func); } }; var _addClass = function (element, value) { if (element.addClass) { element.addClass(value); return element; } if (value && typeof value === "string" ) { var classNames = (value || "" ).split(/\s+/); if (element.nodeType === 1) { if (!element.className) { element.className = value; } else { var className = " " + element.className + " " , setClass = element.className; for ( var c = 0, cl = classNames.length; c < cl; c++) { if (className.indexOf( " " + classNames[c] + " " ) < 0) { setClass += " " + classNames[c]; } } element.className = setClass.replace(/^\s+|\s+$/g, "" ); } } } return element; }; var _removeClass = function (element, value) { if (element.removeClass) { element.removeClass(value); return element; } if (value && typeof value === "string" || value === undefined) { var classNames = (value || "" ).split(/\s+/); if (element.nodeType === 1 && element.className) { if (value) { var className = ( " " + element.className + " " ).replace(/[\n\t]/g, " " ); for ( var c = 0, cl = classNames.length; c < cl; c++) { className = className.replace( " " + classNames[c] + " " , " " ); } element.className = className.replace(/^\s+|\s+$/g, "" ); } else { element.className = "" ; } } } return element; }; var _getZoomFactor = function () { var rect, physicalWidth, logicalWidth, zoomFactor = 1; if ( typeof document.body.getBoundingClientRect === "function" ) { rect = document.body.getBoundingClientRect(); physicalWidth = rect.right - rect.left; logicalWidth = document.body.offsetWidth; zoomFactor = Math.round(physicalWidth / logicalWidth * 100) / 100; } return zoomFactor; }; var _getDOMObjectPosition = function (obj) { var info = { left: 0, top: 0, width: 0, height: 0, zIndex: 999999999 }; var zi = _getStyle(obj, "z-index" ); if (zi && zi !== "auto" ) { info.zIndex = parseInt(zi, 10); } if (obj.getBoundingClientRect) { var rect = obj.getBoundingClientRect(); var pageXOffset, pageYOffset, zoomFactor; if ( "pageXOffset" in window && "pageYOffset" in window) { pageXOffset = window.pageXOffset; pageYOffset = window.pageYOffset; } else { zoomFactor = _getZoomFactor(); pageXOffset = Math.round(document.documentElement.scrollLeft / zoomFactor); pageYOffset = Math.round(document.documentElement.scrollTop / zoomFactor); } var leftBorderWidth = document.documentElement.clientLeft || 0; var topBorderWidth = document.documentElement.clientTop || 0; info.left = rect.left + pageXOffset - leftBorderWidth; info.top = rect.top + pageYOffset - topBorderWidth; info.width = "width" in rect ? rect.width : rect.right - rect.left; info.height = "height" in rect ? rect.height : rect.bottom - rect.top; } return info; }; var _noCache = function (path, options) { var useNoCache = !(options && options.useNoCache === false ); if (useNoCache) { return (path.indexOf( "?" ) === -1 ? "?" : "&" ) + "nocache=" + new Date().getTime(); } else { return "" ; } }; var _vars = function (options) { var str = []; var origins = []; if (options.trustedOrigins) { if ( typeof options.trustedOrigins === "string" ) { origins = origins.push(options.trustedOrigins); } else if ( typeof options.trustedOrigins === "object" && "length" in options.trustedOrigins) { origins = origins.concat(options.trustedOrigins); } } if (options.trustedDomains) { if ( typeof options.trustedDomains === "string" ) { origins = origins.push(options.trustedDomains); } else if ( typeof options.trustedDomains === "object" && "length" in options.trustedDomains) { origins = origins.concat(options.trustedDomains); } } if (origins.length) { str.push( "trustedOrigins=" + encodeURIComponent(origins.join( "," ))); } if ( typeof options.amdModuleId === "string" && options.amdModuleId) { str.push( "amdModuleId=" + encodeURIComponent(options.amdModuleId)); } if ( typeof options.cjsModuleId === "string" && options.cjsModuleId) { str.push( "cjsModuleId=" + encodeURIComponent(options.cjsModuleId)); } return str.join( "&" ); }; var _inArray = function (elem, array) { if (array.indexOf) { return array.indexOf(elem); } for ( var i = 0, length = array.length; i < length; i++) { if (array[i] === elem) { return i; } } return -1; }; var _prepGlue = function (elements) { if ( typeof elements === "string" ) throw new TypeError( "ZeroClipboard doesn't accept query strings." ); if (!elements.length) return [ elements ]; return elements; }; var _dispatchCallback = function (func, element, instance, args, async) { if (async) { window.setTimeout( function () { func.call(element, instance, args); }, 0); } else { func.call(element, instance, args); } }; var ZeroClipboard = function (elements, options) { if (elements) (ZeroClipboard.prototype._singleton || this ).glue(elements); if (ZeroClipboard.prototype._singleton) return ZeroClipboard.prototype._singleton; ZeroClipboard.prototype._singleton = this ; this .options = {}; for ( var kd in _defaults) this .options[kd] = _defaults[kd]; for ( var ko in options) this .options[ko] = options[ko]; this .handlers = {}; if (ZeroClipboard.detectFlashSupport()) _bridge(); }; var currentElement, gluedElements = []; ZeroClipboard.prototype.setCurrent = function (element) { currentElement = element; this .reposition(); var titleAttr = element.getAttribute( "title" ); if (titleAttr) { this .setTitle(titleAttr); } var useHandCursor = this .options.forceHandCursor === true || _getStyle(element, "cursor" ) === "pointer" ; _setHandCursor.call( this , useHandCursor); }; ZeroClipboard.prototype.setText = function (newText) { if (newText && newText !== "" ) { this .options.text = newText; if ( this .ready()) this .flashBridge.setText(newText); } }; ZeroClipboard.prototype.setTitle = function (newTitle) { if (newTitle && newTitle !== "" ) this .htmlBridge.setAttribute( "title" , newTitle); }; ZeroClipboard.prototype.setSize = function (width, height) { if ( this .ready()) this .flashBridge.setSize(width, height); }; ZeroClipboard.prototype.setHandCursor = function (enabled) { enabled = typeof enabled === "boolean" ? enabled : !!enabled; _setHandCursor.call( this , enabled); this .options.forceHandCursor = enabled; }; var _setHandCursor = function (enabled) { if ( this .ready()) this .flashBridge.setHandCursor(enabled); }; ZeroClipboard.version = "1.2.0-beta.4" ; var _defaults = { moviePath: "ZeroClipboard.swf" , trustedOrigins: null , text: null , hoverClass: "zeroclipboard-is-hover" , activeClass: "zeroclipboard-is-active" , allowScriptAccess: "sameDomain" , useNoCache: true , forceHandCursor: false }; ZeroClipboard.setDefaults = function (options) { for ( var ko in options) _defaults[ko] = options[ko]; }; ZeroClipboard.destroy = function () { ZeroClipboard.prototype._singleton.unglue(gluedElements); var bridge = ZeroClipboard.prototype._singleton.htmlBridge; bridge.parentNode.removeChild(bridge); delete ZeroClipboard.prototype._singleton; }; ZeroClipboard.detectFlashSupport = function () { var hasFlash = false ; if ( typeof ActiveXObject === "function" ) { try { if ( new ActiveXObject( "ShockwaveFlash.ShockwaveFlash" )) { hasFlash = true ; } } catch (error) {} } if (!hasFlash && navigator.mimeTypes[ "application/x-shockwave-flash" ]) { hasFlash = true ; } return hasFlash; }; var _amdModuleId = null ; var _cjsModuleId = null ; var _bridge = function () { var client = ZeroClipboard.prototype._singleton; var container = document.getElementById( "global-zeroclipboard-html-bridge" ); if (!container) { var opts = {}; for ( var ko in client.options) opts[ko] = client.options[ko]; opts.amdModuleId = _amdModuleId; opts.cjsModuleId = _cjsModuleId; var flashvars = _vars(opts); var html = ' <object classid= "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" id= "global-zeroclipboard-flash-bridge" width= "100%" height= "100%" > <param name= "movie" value= "' + client.options.moviePath + _noCache(client.options.moviePath, client.options) + '" /> <param name= "allowScriptAccess" value= "' + client.options.allowScriptAccess + '" /> <param name= "scale" value= "exactfit" /> <param name= "loop" value= "false" /> <param name= "menu" value= "false" /> <param name= "quality" value= "best" /> <param name= "bgcolor" value= "#ffffff" /> <param name= "wmode" value= "transparent" /> <param name= "flashvars" value= "' + flashvars + '" /> <embed src= "' + client.options.moviePath + _noCache(client.options.moviePath, client.options) + '" loop= "false" menu= "false" quality= "best" bgcolor= "#ffffff" width= "100%" height= "100%" name= "global-zeroclipboard-flash-bridge" allowScriptAccess= "always" allowFullScreen= "false" type= "application/x-shockwave-flash" wmode= "transparent" pluginspage= "http://www.macromedia.com/go/getflashplayer" flashvars= "' + flashvars + '" scale= "exactfit" > </embed> </object>'; container = document.createElement( "div" ); container.id = "global-zeroclipboard-html-bridge" ; container.setAttribute( "class" , "global-zeroclipboard-container" ); container.setAttribute( "data-clipboard-ready" , false ); container.style.position = "absolute" ; container.style.left = "-9999px" ; container.style.top = "-9999px" ; container.style.width = "15px" ; container.style.height = "15px" ; container.style.zIndex = "9999" ; container.innerHTML = html; document.body.appendChild(container); } client.htmlBridge = container; client.flashBridge = document[ "global-zeroclipboard-flash-bridge" ] || container.children[0].lastElementChild; }; ZeroClipboard.prototype.resetBridge = function () { this .htmlBridge.style.left = "-9999px" ; this .htmlBridge.style.top = "-9999px" ; this .htmlBridge.removeAttribute( "title" ); this .htmlBridge.removeAttribute( "data-clipboard-text" ); _removeClass(currentElement, this .options.activeClass); currentElement = null ; this .options.text = null ; }; ZeroClipboard.prototype.ready = function () { var ready = this .htmlBridge.getAttribute( "data-clipboard-ready" ); return ready === "true" || ready === true ; }; ZeroClipboard.prototype.reposition = function () { if (!currentElement) return false ; var pos = _getDOMObjectPosition(currentElement); this .htmlBridge.style.top = pos.top + "px" ; this .htmlBridge.style.left = pos.left + "px" ; this .htmlBridge.style.width = pos.width + "px" ; this .htmlBridge.style.height = pos.height + "px" ; this .htmlBridge.style.zIndex = pos.zIndex + 1; this .setSize(pos.width, pos.height); }; ZeroClipboard.dispatch = function (eventName, args) { ZeroClipboard.prototype._singleton.receiveEvent(eventName, args); }; ZeroClipboard.prototype.on = function (eventName, func) { var events = eventName.toString().split(/\s/g); for ( var i = 0; i < events.length; i++) { eventName = events[i].toLowerCase().replace(/^on/, "" ); if (! this .handlers[eventName]) this .handlers[eventName] = func; } if ( this .handlers.noflash && !ZeroClipboard.detectFlashSupport()) { this .receiveEvent( "onNoFlash" , null ); } }; ZeroClipboard.prototype.addEventListener = ZeroClipboard.prototype.on; ZeroClipboard.prototype.off = function (eventName, func) { var events = eventName.toString().split(/\s/g); for ( var i = 0; i < events.length; i++) { eventName = events[i].toLowerCase().replace(/^on/, "" ); for ( var event in this .handlers) { if (event === eventName && this .handlers[event] === func) { delete this .handlers[event]; } } } }; ZeroClipboard.prototype.removeEventListener = ZeroClipboard.prototype.off; ZeroClipboard.prototype.receiveEvent = function (eventName, args) { eventName = eventName.toString().toLowerCase().replace(/^on/, "" ); var element = currentElement; var performCallbackAsync = true ; switch (eventName) { case "load" : if (args && parseFloat(args.flashVersion.replace( "," , "." ).replace(/[^0-9\.]/gi, "" )) < 10) { this .receiveEvent( "onWrongFlash" , { flashVersion: args.flashVersion }); return ; } this .htmlBridge.setAttribute( "data-clipboard-ready" , true ); break ; case "mouseover" : _addClass(element, this .options.hoverClass); break ; case "mouseout" : _removeClass(element, this .options.hoverClass); this .resetBridge(); break ; case "mousedown" : _addClass(element, this .options.activeClass); break ; case "mouseup" : _removeClass(element, this .options.activeClass); break ; case "datarequested" : var targetId = element.getAttribute( "data-clipboard-target" ), targetEl = !targetId ? null : document.getElementById(targetId); if (targetEl) { var textContent = targetEl.value || targetEl.textContent || targetEl.innerText; if (textContent) this .setText(textContent); } else { var defaultText = element.getAttribute( "data-clipboard-text" ); if (defaultText) this .setText(defaultText); } performCallbackAsync = false ; break ; case "complete" : this .options.text = null ; break ; } if ( this .handlers[eventName]) { var func = this .handlers[eventName]; if ( typeof func === "string" && typeof window[func] === "function" ) { func = window[func]; } if ( typeof func === "function" ) { _dispatchCallback(func, element, this , args, performCallbackAsync); } } }; ZeroClipboard.prototype.glue = function (elements) { elements = _prepGlue(elements); for ( var i = 0; i < elements.length; i++) { if (_inArray(elements[i], gluedElements) == -1) { gluedElements.push(elements[i]); _addEventHandler(elements[i], "mouseover" , _elementMouseOver); } } }; ZeroClipboard.prototype.unglue = function (elements) { elements = _prepGlue(elements); for ( var i = 0; i < elements.length; i++) { _removeEventHandler(elements[i], "mouseover" , _elementMouseOver); var arrayIndex = _inArray(elements[i], gluedElements); if (arrayIndex != -1) gluedElements.splice(arrayIndex, 1); } }; if ( typeof define === "function" && define.amd) { define([ "require" , "exports" , "module" ], function (require, exports, module) { _amdModuleId = module && module.id || null ; return ZeroClipboard; }); } else if ( typeof module !== "undefined" && module) { _cjsModuleId = module.id || null ; module.exports = ZeroClipboard; } else { window.ZeroClipboard = ZeroClipboard; } })(); |
在开发使用该插件中。由于没仔细。导致报错
TypeError: document.body is null_js报错解决办法
遇到这样的错误。解决方法就是,把该插件引用的js文件和js代码都写在</body>后面
1.首先引入插件的js代码
1 | <script type= "text/javascript" src= "<%=request.getContextPath()%>/jslib/zeroclipboard/ZeroClipboard.js" ></script> |
2.html代码
1 2 3 4 5 6 | < input type = "text" id = "demo" name = "demo" > < div class = "copy-button-section" > < button id = "d_clip_buttons" data-clipboard-target = "demo" class = "my_clip_button" > 复制链接及密码 </ button > </ div > |
<input type="text" id="demo"name="demo">
<div class="copy-button-section">
<button id="d_clip_buttons" data-clipboard-target="demo" class="my_clip_button">
复制链接及密码
</button>
</div>
data-clipboard-target红色标注的内容为要复制 指定input的id
3.js调用插件的方法实现功能
1 2 3 4 5 6 7 8 9 10 | <script type= "text/javascript" > //定义一个复制对象 var clip = null ; clip = new ZeroClipboard($( "#d_clip_button" ),{ moviePath: '<%=request.getContextPath()%>/jslib/zeroclipboard/ZeroClipboard.swf' }); clip.on( 'complete' , function (client,args){ alert( '复制成功' ); }); </script> |
4.data属性说明
名称 | 说明 |
---|---|
data-clipboard-target | 元素ID。查找该元素后,尝试复制元素的 .value 或 .textContent 或.innerText 的值 |
data-clipboard-text | 默认复制的内容。 |
同时设置 data-clipboard-target 和 data-clipboard-text 两个属性时,只有在找不到 clipboard-target 的值时才会选用 clipboard-text
即使获取到 clipboard-target 的值为空,也不会选用 clipboard-text
5.一个中文API的网站
http://code.ciaoca.com/javascript/zeroclipboard/