JavaScript - 从SweetAlert2按钮确认复制

3

当按下“复制URL”按钮后,我该如何复制它所包含的内容?

function cdwUrlsMDBE() {
            var prd = document.getElementById("prd");

            if (prd.checked == true) {
                Swal.fire({
                    type: 'success',
                    html: 'i am a text that should be copy',
                    width: 'auto',
                    confirmButtonText: 'Copy URLs',
                })

谢谢


你想让复制按钮只在“复制URL”被点击后才能复制吗?请查看此处的 onClose https://sweetalert2.github.io/#configuration,然后像这篇博客中的示例函数一样添加一些内容 https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f。 - Clay
2个回答

1
您可以通过htmlBootstrap创建一个按钮来实现它,这样您就可以通过onOpen在按钮上附加一个处理程序。

像这样的东西

Swal.fire({
    title: "Copy it!",
    html: 
        '<textarea id="text_to_be_copied" class="swal2-input" readonly>Some text you want to copy</textarea>' +
            '<button type="button" class="btn btn-default" id="btn-copy" style="margin-left:5px">Copy</button>' +
            '<button type="button" class="btn btn-primary swal-confirm" id="btn-ok" style="float:right" disabled>Text have been copied!</button>' +
        '</div>',
    showConfirmButton: false,
    type: "success",
    onOpen: () => {
        $("#btn-copy").click(() => {
            $("#btn-ok").prop('disabled', false);

            $("#text_to_be_copied").select();
            document.execCommand("copy");
        });

        $("#btn-ok").click(() => {
            Swal.close();   
        });
    }
});

这样,只有在使用复制按钮后才会显示“确认按钮”,但您可以通过在复制按钮的处理程序中放置Swal.close()来决定摆脱它。这样,在单击复制按钮后,弹出窗口将关闭。

根据您的需求,您可以选择使用输入标记而不是文本区域。


0
var txtToBeCopied ='i am a text that should be copy';

    if (prd.checked == true) {
                Swal.fire({
                    type: 'success',
                    html: txtToBeCopied,
                    width: 'auto',
                    confirmButtonText: 'Copy URLs',
                },
 function(isConfirm){

   if (isConfirm){

     /* Get the text field */
  var copyText = txtToBeCopied;

  /* Select the text field */
  copyText.select();
  copyText.setSelectionRange(0, 99999); /*For mobile devices*/

  /* Copy the text inside the text field */
  document.execCommand("copy");


    }
 })
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接