当前位置:迷你笔记 » 杂谈 » 如何用JS优雅复制内容?

如何用JS优雅复制内容?

<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.4.0/clipboard.min.js" integrity="sha512-iJh0F10blr9SC3d0Ow1ZKHi9kt12NYa+ISlmCdlCdNZzFwjH1JppRTeAnypvUez01HroZhAmP4ro4AvZ/rG0UQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
// elegant copy with high compatibility
    document.addEventListener('DOMContentLoaded', function() {
        var copyButtons = document.querySelectorAll('.copybutton');
        function addCopyEvent(button) {
            button.style.position = 'relative';
            button.addEventListener('click', function() {
                var content = document.querySelector('.copycontent');
                if (content) {
                    if (document.body.createTextRange) { // IE compatibility
                        var range = document.body.createTextRange();
                        range.moveToElementText(content);
                        range.select();
                        document.execCommand('copy');
                    } else if (window.getSelection && document.execCommand) { // Standard browsers
                        var selection = window.getSelection();
                        var range = document.createRange();
                        range.selectNodeContents(content);
                        selection.removeAllRanges();
                        selection.addRange(range);
                        document.execCommand('copy');
                        selection.removeAllRanges();
                    }
                    var tooltip = document.createElement('div');
                    tooltip.className = 'copy-tooltip';
                    tooltip.innerHTML = 'Copied!';
                    button.appendChild(tooltip);

                    tooltip.style.top = '50%';
                    tooltip.style.left = '50%';
                    tooltip.style.transform = 'translate(-50%, -50%)';

                    setTimeout(function() {
                        if (tooltip.parentNode) {
                            tooltip.parentNode.removeChild(tooltip);
                        }
                    }, 1500);
                }
            });
        }
        copyButtons.forEach(addCopyEvent);
    });
</script>
<style>
.copybutton {
    cursor: pointer;
}
.copy-tooltip {
    position: absolute;
    background: rgba(76, 175, 80, 0.8);
    color: #fff;
    padding: 3px 3px;
    border-radius: 5px;
    text-align: center;
    pointer-events: none;
    z-index: 10;
    min-width: 210px;
}
</style>

国内环境用https://cdn.staticfile.net/clipboard.js/1.4.0/clipboard.min.js

未经允许不得转载:迷你笔记 » 如何用JS优雅复制内容?

相关文章

评论 (0)

3 + 8 =