无法将数据属性复制到剪贴板

问题描述 投票:0回答:1
javascript clipboard
1个回答
0
投票

document.execCommand('copy') 方法现在被认为已过时,并且可能无法在某些现代浏览器中工作。相反,您可以使用较新的剪贴板 API 来实现此目的。

function copyToClipboard(obj) {
    var text = $(obj).data('copy-to-clipboard');

    // Using Clipboard API
    navigator.clipboard.writeText(text)
        .then(() => {
            console.log('Text successfully copied to clipboard:', text);
        })
        .catch((err) => {
            console.error('Unable to copy text to clipboard', err);
        });
}

// Alternatively, using jQuery
$(document).ready(function () {
    $('.text-info').on('click', function () {
        var text = $(this).data('copy-to-clipboard');

        // Using jQuery and document.execCommand
        var $tempInput = $('<input>');
        $('body').append($tempInput);
        $tempInput.val(text).select();
        document.execCommand('copy');
        $tempInput.remove();

        console.log('Text successfully copied to clipboard:', text);
    });
});
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <a class="text-info mr-2" href="javascript:void(0);" data-copy-to-clipboard="Hello World" onclick="copyToClipboard(this);"><i class="bx bx-copy me-1"></i>Copy Text</a>

© www.soinside.com 2019 - 2024. All rights reserved.