Javascript - 从 sweetalert2 复制按钮确认

Javascript - copy from sweetalert2 button confirm

如何在单击按钮 "Copy URLs" 时复制?

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',
                })

谢谢

您可以通过 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();   
        });
    }
});

这样 "confirmation button" 仅在您使用复制按钮后显示,但您可以决定通过将 Swal.close() 放入复制按钮的处理程序中来摆脱它。这样点击复制按钮后,弹窗就会关闭。

您也可以根据需要选择使用输入标签而不是文本区域。

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");


    }
 })
 }