自定义JavaScript提示和确认框

Customize javascript prompt and confirmation box

本文关键字:确认 提示 JavaScript 自定义      更新时间:2023-09-26

我对HTML设计很陌生。我的前端是Angular.js。在我的应用程序中,执行了一些方法并提示用户输入。用户输入后,它继续执行其余逻辑。

目前,我正在使用简单的confirm()prompt()。但是我需要有html模板而不是典型的消息。我尝试了如下内容。

var htmlStr = "<div> This is nice html with <h1>header</h1> and body content </div>";
var action = prompt(htmlStr);  

它显示为字符串而不是 html。

知道如何转换为 html?欢迎任何帮助/建议。

是不可能的。在promptalertconfirm弹出窗口中修改文本的范围仅限于向字符串中添加'n字符以添加分隔线。(可能是其他一些转义字符,但不允许使用 html。这些弹出窗口的样式完全取决于浏览器。

window.prompt()

您可以做的是使用根据自己的喜好设置样式的position:absoluterelativediv创建自定义模态。

您可以使用 sweetalert 显示自定义 JavaScript 提示或确认框。

swal({
    title: "An input!",
    text: "Write something interesting:",
    type: "input",   showCancelButton: true,
    closeOnConfirm: false,
    animation: "slide-from-top",
    inputPlaceholder: "Write something" },
    function (inputValue) {
        if(inputValue === false) {
            return false;
        }
        if(inputValue === "") {
            swal.showInputError("You need to write something!");
            return false;
        }
        swal("Nice!", "You wrote: " + inputValue, "success");
    }
);

演示 https://jsfiddle.net/szf1jgog/

document.querySelector('button').onclick = function() {
  swal({
      title: "An input!",
      text: 'Write something interesting:',
      type: 'input',
      showCancelButton: true,
      closeOnConfirm: false,
      animation: "slide-from-top",
      inputPlaceholder: "Write something",
    },
    function(inputValue) {
      if (inputValue === false) return false;
      if (inputValue === "") {
        swal.showInputError("You need to write something!");
        return false;
      }
      swal("Nice!", 'You wrote: ' + inputValue, "success");
    });
};
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<button>Alert me</button>

提示方法仅接受字符串作为其参数,因此,您传入的任何html代码也将仅被视为字符串。如果你的项目是用angularjs的,那么我建议你看看angular-ui Bootstrap

这为所有常见用例提供了本机角度指令。可以使用modal获取用户输入并根据需要设置其样式。