1. 程式人生 > >通過如何通過js實現複製貼上功能

通過如何通過js實現複製貼上功能

在ie中window.clipboardData(剪下板物件)是可以被獲取,所以利用這個方法我們可以實現在IE當中複製貼上的功能,demo如下!

複製程式碼
<html>   
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">   
<title>clipboard</title>   
<SCRIPT language=JavaScript>   
function copy()   
{   
  var obj=document.getElementById(
"txarea"); window.clipboardData.setData("Text",obj.value);//設定資料 alert("複製成功"); } function paste() { var obj=document.getElementById("txarea"); var clipboard = window.clipboardData.getData('Text'); clipboard == null ? alert('no data') : obj.value = clipboard; } </SCRIPT
> <INPUT name=Button onClick="txarea.value=''" type=button value='clear'> <INPUT name=Button onClick="copy('textarea')" type=button value='copy'> <INPUT name=Button onClick="paste('textarea')"; type=button value='paste'><br> <textarea name="txarea" id="txarea"
cols="105" rows="11" class="transform"></textarea></p> </body> </html>
複製程式碼

上述程式碼在IE中訪問是可以實現複製貼上的!但是其他瀏覽器並不被支援!於是找了下資料,由於現在瀏覽器種類也越來越多,諸如 IE、Firefox、Chrome、Safari等等,因此現在要實現一個js複製內容到剪貼簿的小功能就不是一件那麼容易的事了。 在FLASH 9 時代,有一個通殺所有瀏覽器的js複製內容到剪貼簿的方案:這個方案是一個最流行的方法: 著名的Clipboard Copy解決方案 利用一個clipboard.swf作為橋樑,複製內容到剪貼簿。原理是:建立一個隱藏的flash檔案,同時給給flash的變數FlashVars 賦“clipboard=..”,通過這個賦值flash就會把複製的內容放到剪貼簿。這個方法相容IE、Firefox、Opera、chrome、 Safari,真可謂“萬能”的解決方案。瀏覽器Flash的安裝率非常高,這幾乎是一個完美的解決方案。

demo如下所示:

複製程式碼
<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta name="copyright" content=""/>
    <title>複製貼上</title>
    <body>
       <div class="one">
        <input type="text" class="gift_num fl" value="XXXXXXXXXXXXXXXXXXXXXX" disabled="disabled" readonly="true"/>
        <a href="javascript:;" hidefocus="none" class="btn_copy block fl" id="btnCopy">複製</a>    
       </div>
    </body>
</html>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="ZeroClipboard.js"></script>
<script type="text/javascript">
//這裡的引數說明一下,text是要複製的文字內容,button是點選觸發複製的dom物件,msg是複製成功後的提示資訊,parent是包含flash的父元素
function clipboard(text, button, msg, parent) {
    if (window.clipboardData) {//如果是IE瀏覽器
        var copyBtn = document.getElementById(button);
        copyBtn.onclick = function() {
            window.clipboardData.setData('text', text);
            alert(msg);
        }
    } else {//非IE瀏覽器
        var clip = new ZeroClipboard.Client();//初始化一個剪下板物件
        clip.setHandCursor(true);//設定手型遊標
        clip.setText(text);//設定待複製的文字內容
        clip.addEventListener("mouseUp", function(client) {//繫結mouseUp事件觸發複製
            alert(msg);
        });
        clip.glue(button,parent);//呼叫ZeroClipboard.js的內建方法處理flash的位置的問題
    }
    return false;
}
$(function(){
    clipboard($(".gift_num").val(),"btnCopy","複製成功",'btnCopy');//呼叫方式
})
</script>
複製程式碼

針對上面的demo,我修改了下ZeroClipboard.js外掛裡面的程式碼,以便能在不確定複製按鈕在什麼位置的情況下可以使用!程式碼如下:紅色是修改過的程式碼

複製程式碼
var ZeroClipboard = {
    version: "1.0.7",
    clients: {},
    moviePath: '/js/ZeroClipboard.swf',
    nextId: 1,
    $: function(thingy) {
        if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
        if (!thingy.addClass) {
            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) {
        this.moviePath = path;
    },
    dispatch: function(id, eventName, args) {
        var client = this.clients[id];
        if (client) {
            client.receiveEvent(eventName, args);
        }
    },
    register: function(id, client) {
        this.clients[id] = client;
    },
    getDOMObjectPosition: function(obj, stopObj) {
        var info = {
            left: 0,
            top: 0,
            width: 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;
            console.log(obj);
            console.log(stopObj);
        }
        return info;
    },
    Client: function(elem) {
        this.handlers = {};
        this.id = ZeroClipboard.nextId++;
        this.movieId = 'ZeroClipboardMovie_' + this.id;
        ZeroClipboard.register(this.id, this);
        if (elem) this.glue(elem);
    }
};
ZeroClipboard.Client.prototype = {
    id: 0,
    ready: false,
    movie: null,
    clipText: '',
    handCursorEnabled: true,
    cssEffects: true,
    handlers: null,
    glue: function(elem, appendElem, stylesToAdd) {
        this.domElement = ZeroClipboard.$(elem);
        var zIndex = 9999;
        if (this.domElement.style.zIndex) {
            zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
        }
        if (typeof(appendElem) == 'string') {
            if(!($('#'+ appendElem).css("position") == 'relative' || $('#'+ appendElem).css("position") == 'absolute')){
               $('#'+ appendElem).css("position","relative");//如果指定的父元素不是相對和決定定位就設定父元素為相對定位
            }
            appendElem = ZeroClipboard.$(appendElem);
        } else if (typeof(appendElem) == 'undefined') {
            appendElem = document.getElementsByTagName('body')[0];
        }
        var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem);
        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];
            }
        }
        appendElem.appendChild(this.div);
        this.div.innerHTML = this.getHTML(box.width, box.height);
    },
    getHTML: function(width, height) {
        var html = '';
        var flashvars = 'id=' + this.id + '&width=' + width + '&height=' + height;
        if (navigator.userAgent.match(/MSIE/)) {
            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 {
            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() {
        if (this.div) {
            this.div.style.left = '-2000px';
        }
    },
    show: function() {
        this.reposition();
    },
    destroy: function() {
        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) {
        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) {
        this.clipText = newText;
        if (this.ready) this.movie.setText(newText);
    },
    addEventListener: function(eventName, func) {
        eventName = eventName.toString().toLowerCase().replace(/^on/, '');
        if (!this.handlers[eventName]) this.handlers[eventName] = [];
        this.handlers[eventName].push(func);
    },
    setHandCursor: function(enabled) {
        this.handCursorEnabled = enabled;
        if (this.ready) this.movie.setHandCursor(enabled);
    },
    setCSSEffects: function(enabled) {
        this.cssEffects = !!enabled;
    },
    receiveEvent: function(eventName, args) {
        eventName = eventName.toString().toLowerCase().replace(/^on/, '');
        switch (eventName) {
            case 'load':
                this.movie = document.getElementById(this.movieId);
                if (!this.movie) {
                    var self = this;
                    setTimeout(function() {
                        self.receiveEvent('load', null);
                    }, 1);
                    return;
                }
                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;
        }
        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') {
                    func(this, args);
                } else if ((typeof(func) == 'object') && (func.length == 2)) {
                    func[0][func[1]](this, args);
                } else if (typeof(func) == 'string') {
                    window[func](this, args);
                }
            }
        }
    }
};
複製程式碼

說明:父元素的設定一般情況下就是點選複製的按鈕,如有其它的情況下可以修改相應的程式碼來適合自己的需求!

上述是在前輩已經成熟的程式碼的基礎上做了相應的修改

此方法的要在伺服器環境下才可以看到效果!