javascript - 如何将 SweetAlert 与 Clipboard.js 库一起使用?

标签 javascript jquery html sweetalert clipboard.js

我正在尝试使用 SweetAlertclipboard.js图书馆。 我尝试过在用户在 SweetAlert 上确认时模拟单击 HTML 按钮,但没有成功。

这是我尝试做的:

我的 HTML:

<button class="btn btn-primary" id="copyBtn" data-clipboard-target="#info_block" onclick="copyText();">
    Copy Text!
</button>

<div id="info_block" name="info_block">
    Some example text.
</div>

我的 JavaScript 函数:

var clipboard = new Clipboard('.btn');
clipboard.on('success', function(e) {
    console.log(e);
});
clipboard.on('error', function(e) {
    console.log(e);
});

我的 SweetAlert 的结构:

swal({
  title: "Copy the text?",
  text: "Are you sure you want to copy it to clipboard?",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Yes, copy it!",
  closeOnConfirm: false
},
function(){
  $("#copyBtn").click(); // simulates click on html button.
  swal("Copied!", "The text has been copied.", "success");
});

它在没有甜蜜警报的情况下工作正常,但它无法模拟单击复制按钮,而且我无法找到让它工作的方法。

最佳答案

通过此变体,可以使用较新的 SweetAlert2.js。

function copyText(){

    var copy = $('.copy_text').val();
    $('.copy_text').select();
    document.execCommand('copy');
    
    Swal.fire({
        icon: 'success',
        title: 'Text copied to clipboard',
        text: copy,
        showConfirmButton: false,
        timer: 3000
    });
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>

<input type="text" class="copy_text" value="Hello World!">
<button onclick="copyText()">Copy to clipboard</button>

关于javascript - 如何将 SweetAlert 与 Clipboard.js 库一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45228076/

相关文章:

javascript - 如何使用 Node 将表单数据(文本/纯文本)转换为json?

javascript - 固定位置在 IE 中不起作用

javascript - 使用jQuery UI Draggable,使用滚动条时如何避免拖动?

html - 底部边框应该显示一半。如何?

javascript - jQuery:删除点击时可调整大小的句柄并在点击时添加它们?

javascript - 不存在 'Access-Control-Allow-Origin' header - 使用 AJAX 调用 Food2Fork API

javascript - Jquery 顶部导航在滚动条上消失

javascript - iOS Phonegap 使用手势滑动检测

Android 操作系统键盘将网站内容向上移动?

html - 如何在图像上创建响应式 div?