JavaScript实现复制、剪切和粘贴

需求描述

项目中需要实现一个点击按钮复制链接的功能,网上看到的几款插件,ZeroClipboard是通过flash实现的复制功能,随着越来越多的提议废除flash,能不能通过js来实现复制剪切呢,今天分享一个兼容IE7浏览器复制的插件给大家,支持使用JavaScript实现复制、剪切和粘贴。

地址:https://github.com/baixuexiyang/clipBoard.js

浏览器支持

copy cut paste
chrome ×
Firefox ×
IE7+

方法

copy

var copy = new clipBoard(document.getElementById('data'), {
    beforeCopy: function() {

    },
    copy: function() {
        return document.getElementById('data').value;
    },
    afterCopy: function() {

    }
});

copy will be called automatic, if you want call by yourself, you can do like this

var copy = new clipBoard(document.getElementById('data'));
copy.copyd();

document.getElementById(‘data’) :要获取的对象, 你也可以使用jQuery $(‘#data’)

cut

it same to copy

var cut = new clipBoard(document.getElementById('data'), {
    beforeCut: function() {

    },
    cut: function() {
        return document.getElementById('data').value;
    },
    afterCut: function() {

    }
});

or

var cut = new clipBoard(document.getElementById('data'));
cut.cut();

paste

var paste = new clipBoard(document.getElementById('data'), {
    beforePaste: function() {

    },
    paste: function() {
        return document.getElementById('data').value;
    },
    afterPaste: function() {

    }
});

or

var paste = new clipBoard(document.getElementById('data'));
paste.paste();

完整代码:

/**
 * clipboard.js 
 * width clipboard.js, you can copy cut and paste clipboard data
 * the main methods ard execCommand for modern browser and clipboardData for ie
 * @author ganzw@gmail.com
 * @url    https://github.com/baixuexiyang/clipBoard.js
 */
;(function(name, fun) {
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = fun();
    } else if (typeof define === 'function' && define.amd) {
        define(fun);
    } else {
        this[name] = fun();
    }
})('clipBoard', function() {
    "use strict";

    /**
     * tar is the value
     * @date   2016-04-25
     * @param  {[type]}   tar     [description]
     * @param  {[type]}   options [description]
     * @return {[type]}           [description]
     */
    function clipBoard(tar, options) {
        this.options = options || {};
        this.tar = tar[0] || tar;
        // if options contain copy, copy will be applied soon
        if (this.options.copy) {
            this.copyd();
        }
        if(this.options.cut) {
        	this.cut();
        }

        if(this.options.paste) {
        	this.paste();
        }
    }

    /**
     * coping is to set the value to clipboard
     * you can set the value through copy function, and the function be called autoly
     * Also you can set the paramer and it will be set the clipboard
     */
    clipBoard.prototype.copyd = function(value) {
        // before the copy it will be called, you can check the value or modify the value
        if (this.options.beforeCopy) {
            this.options.beforeCopy();
        }
        // if the options set copy function, the value will be set. then get the paramer value.
        // above all, if the value is null, then will be set the tar of value
        value = value || this.tar.value || this.tar.innerText;
        if (this.options.copy) {
            value = this.options.copy();
        }
        // for modern browser
        if (document.execCommand) {
            var element = document.createElement('SPAN');
            element.textContent = value;
            document.body.appendChild(element);
            if (document.selection) {
                var range = document.body.createTextRange();
                range.moveToElementText(element);
                range.select();
            } else if (window.getSelection) {
                var range = document.createRange();
                range.selectNode(element);
                window.getSelection().removeAllRanges();
                window.getSelection().addRange(range);
            }
            document.execCommand('copy');
            element.remove ? element.remove() : element.removeNode(true);
        }
        // for ie
        if (window.clipboardData) {
            window.clipboardData.setData('text', value);
        }
        // after copy
        if (this.options.afterCopy) {
            this.options.afterCopy();
        }
    };
    /**
     * cut the value of input or textarea
     * @date   2016-04-25
     * @return {[type]}   [description]
     */
    clipBoard.prototype.cut = function() {
        if (this.tar.type !== 'text' && this.tar.type !== 'textarea') {
            return;
        }
        if (this.options.beforeCut) {
            this.options.beforeCut();
        }
        if (document.execCommand) {
            var element = this.tar;
            if (document.selection) {
                var range = document.body.createTextRange();
                range.moveToElementText(element);
                range.select();
            } else if (window.getSelection) {
                element.select();
            }
            document.execCommand('cut');
        }
        // for ie
        if (window.clipboardData) {
            window.clipboardData.setData('text', this.tar.value);
            this.tar.value = '';
        }
        // after copy
        if (this.options.afterCut) {
            this.options.afterCut();
        }
    };

    /**
     * paste the clipboard value to input or textarea
     * @date   2016-04-25
     * @return {[type]}   [description]
     */
    clipBoard.prototype.paste = function() {
    	if (this.tar.type !== 'text' && this.tar.type !== 'textarea') {
            return;
        }
        if (this.options.beforePaste) {
            this.options.beforePaste();
        }
        if (document.execCommand) {
            var element = this.tar;
            if(element.setSelectionRange) {
           		element.focus();
           		element.setSelectionRange(element.value.length, element.value.length);
    		} else if (element.createTextRange) {
    			var range = element.createTextRange();
    			range.collapse(true);
    			range.moveEnd('character', element.value.length);
    			range.moveStart('character', element.value.length);
    			range.select();
           	}
            document.execCommand('paste');
        }
        // for ie
        if (!document.execCommand && window.clipboardData) {
            this.tar.value +=  window.clipboardData.getData('text');
        }
        // after Paste
        if (this.options.afterPaste) {
            this.options.afterPaste();
        }
    };

    return clipBoard;
});

关注我

我的微信公众号:前端开发博客,在后台回复以下关键字可以获取资源。

  • 回复「小抄」,领取Vue、JavaScript 和 WebComponent 小抄 PDF
  • 回复「Vue脑图」获取 Vue 相关脑图
  • 回复「思维图」获取 JavaScript 相关思维图
  • 回复「简历」获取简历制作建议
  • 回复「简历模板」获取精选的简历模板
  • 回复「加群」进入500人前端精英群
  • 回复「电子书」下载我整理的大量前端资源,含面试、Vue实战项目、CSS和JavaScript电子书等。
  • 回复「知识点」下载高清JavaScript知识点图谱

每日分享有用的前端开发知识,加我微信:caibaojian89 交流