Copy to clipboard without Flash

后端 未结 8 926
情深已故
情深已故 2020-11-28 05:28

I found many solutions for copying to the clipboard, but they all either with flash, or for websites side. I\'m looking for method copy to clipboard automatically, without f

8条回答
  •  一向
    一向 (楼主)
    2020-11-28 06:20

    I had tryed the flash solution and I don't liked too. Too complex and too slow. What I did was to create a textarea, put the data into that and use the browser "CTRL + C" behavior.

    The jQuery javascript part:

    // catch the "ctrl" combination keydown
    $.ctrl = function(key, callback, args) {
        $(document).keydown(function(e) {
            if(!args) args=[]; // IE barks when args is null
            if(e.keyCode == key && e.ctrlKey) {
                callback.apply(this, args);
                return false;
            }
        });
    };
    
    // put your data on the textarea and select all
    var performCopy = function() {
        var textArea = $("#textArea1");
        textArea.text('PUT THE TEXT TO COPY HERE. CAN BE A FUNCTION.');
        textArea[0].focus();
        textArea[0].select();
    };
    
    // bind CTRL + C
    $.ctrl('C'.charCodeAt(0), performCopy);
    

    The HTML part:

    Now, put what do you want to copy in 'PUT THE TEXT TO COPY HERE. CAN BE A FUNCTION.' area. Works fine for me me. You just have to make one CTRL+C combination. The only drawback is that you are going to have an ugly textarea displayed in you site. If you use the style="display:none" the copy solution will not work.

提交回复
热议问题