標籤:
最近做的一個項目需要用javascript來實現自動複製文本到剪下板,但測試時發現只有ie6.0支援。
到百度搜尋後才發現,原來ie7.0、firefox是不支援這樣的操作的,隨後又搜尋了一下,找到一個解決辦法:
通過javascript調用Flash來複製文本到剪下板。
在HTML代碼中需注意事項:
在OBJECT標籤中,插入id="fcopy"
在EMBED標籤中,插入name="fcopy"和swLiveConnect="true",確保沒有使用id屬性!
Flash代碼:
//匯入ExternalInterface類import flash.external.ExternalInterface;function copy(str){System.setClipboard(str);getURL("javascript:alert(‘已複製,請使用Ctrl+V粘貼出來‘)");}
//允許js中的flAlert()調用flash中的showAlert()
ExternalInterface.addCallback("copy",null,copy);
HTML代碼:
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" id="fcopy" width="1" height="1"><param name="movie" value="flash/clipboard.swf"><param name="quality" value="high"><param name="swLiveConnect" value="true"><embed src="flash/clipboard.swf" width="1" height="1" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" name="fcopy" swLiveConnect="true"></embed></object>
js代碼:
var browser = new Object();function getBrowser() {var b = navigator.userAgent.toLowerCase();browser = { safari: /webkit/.test(b), opera: /opera/.test(b), ie6: /msie 6/.test(b) && !/opera/.test(b), ie7: /msie 7/.test(b) && !/opera/.test(b), msie: /msie/.test(b) && !/opera/.test(b), mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b)};}getBrowser() ;//複製到剪下板function copyCode(field) { field.select();var text=field.value;if(browser.ie6) { window.clipboardData.setData(‘text‘,text) alert(‘已複製,請使用Ctrl+V粘貼出來‘) ;}else{ flashCopy(text); //採用flash方式複製}}//調用flash中的方法,"fcopy"為html頁中swf的idfunction flashCopy(text) {thisMovie("fcopy").copy(text);}//搭建js與flash互連的環境function thisMovie(movieName) {if (navigator.appName.indexOf("Microsoft") != -1) {return window[movieName]}else{return document[movieName]}}
Flash與JavaScript互動