Tooltips + Highlight Animation With Clipboard.js Click

前端 未结 2 1483
清歌不尽
清歌不尽 2020-12-13 13:57

I\'ve successfully installed clipboard.js and have gotten snippets of text to copy to the clipboard upon click. I\'m going to be nesting these snippets of text (or the \"btn

2条回答
  •  不知归路
    2020-12-13 14:48

    I've come up with a slight improvement to Zeno's code, which wraps it in a jQuery function, and supports copying from an arbitrary element:

    if (typeof $.uf === 'undefined') {
        $.uf = {};
    }
    
    $.uf.copy = function (button) {
        var _this = this;
    
        var clipboard = new ClipboardJS(button, {
            text: function(trigger) {
                var el = $(trigger).closest('.js-copy-container').find('.js-copy-target');
                if (el.is(':input')) {
                    return el.val();
                } else {
                    return el.html();
                }
            }
        });
    
        clipboard.on('success', function(e) {
            setTooltip(e.trigger, 'Copied!');
            hideTooltip(e.trigger);
        });
    
        clipboard.on('error', function(e) {
            setTooltip(e.trigger, 'Failed!');
            hideTooltip(e.trigger);
        });
    
        function setTooltip(btn, message) {
            $(btn)
            .attr('data-original-title', message)
            .tooltip('show');
        }
        
        function hideTooltip(btn) {
            setTimeout(function() {
                $(btn).tooltip('hide')
                .attr('data-original-title', "");
            }, 1000);
        }
    
        // Tooltip
        $(button).tooltip({
            trigger: 'click'
        });
    };
    
    // Link all copy buttons
    $.uf.copy('.js-copy-trigger');
    
    
    
    
    
    

    You'll notice that we have our button with a class of js-copy-trigger, and the text/control to be copied with the js-copy-target class. Both of these are wrapped in a common js-copy-container class.

    This is much better than using id targets, because you often need to generate multiple copy buttons (for example, in a table), and ids must be unique on a page.

提交回复
热议问题