如果你也厌倦了alert,那就试试SweetAlert!

AdminPi, 前端, 2021-04-02 18:20:00

SweetAlert,一个漂亮的alert替代品!不过还有一个叫SweetAlert2,功能比SweetAlert更强大,用法类似,不过,一般SweetAlert也就足够用了。

下面罗列一些常用的用法:

1.最基本的弹框:

swal("Hello SweetAlert!");

2.带标题的弹出框:

swal("Hello SweetAlert!","A beautiful replacement for alert");

3.带图标的弹框(有四个预定义的图标,分别为:warning、error、success和info):

swal("Hello SweetAlert!" , "A beautiful replacement for alert...","success");

4.没有按钮的弹框:

swal("Hello SweetAlert!" , {button: false,});

5.延时自动关闭的弹框(单位:毫秒):

swal("Hello SweetAlert!" , {button: false, timer: 2000});

6.带输入框的弹框:

swal({content: "input",}).then((value) => {swal(`The returned value is: ${value}`);});

7.带确认和取消的弹框:

swal("Hello SweetAlert!" , {buttons: ["取消", "确认"],}).then((value) => {if(value){swal("确认");}else{swal("取消");}});

以上这七种,基本就够日常使用了,如果还有更多个性化的需求,可以参考官网API:https://sweetalert.js.org/docs/

贴一下完整版的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文档标题</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
</head>
<body>
  <h1>Hello SweetAlert!</h1>
  <button type="button" onclick='swal("Hello SweetAlert!");'>示例1</button><br /><br />
  <button type="button" onclick='swal("Hello SweetAlert!" , "A beautiful replacement for alert...");'>示例2</button><br /><br />
  <button type="button" onclick='swal("Hello SweetAlert!" , "A beautiful replacement for alert...","success");'>示例3</button><br /><br />
  <button type="button" onclick='swal("Hello SweetAlert!" , {button: false});'>示例4</button><br /><br />
  <button type="button" onclick='swal("Hello SweetAlert!" , {button: false, timer: 2000});'>示例5</button><br /><br />
  <button type="button" onclick='swal({content: "input",}).then((value) => {swal(`The returned value is: ${value}`);});'>示例6</button><br /><br />
  <button type="button" onclick='swal("Hello SweetAlert!" , {buttons: ["取消", "确认"],}).then((value) => {if(value){swal("确认");}else{swal("取消");}});'>示例7</button><br /><br />
</body>
</html>

© 2024