我正在尝试使用 SweetAlert与 clipboard.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/