没有取消按钮的Javascript提示框

Javascript prompt box without the cancel button?

本文关键字:Javascript 提示 按钮 取消      更新时间:2024-04-02

有没有办法创建一个没有取消按钮的输入提示框,或者在输入某个值之前不允许用户关闭提示?

promt放入while循环中,并继续请求输入,直到用户给出任何输入为止。

do{
    input = prompt("Give input");
}while(input == null || input == "" );
console.log(input);

jsFiddle

[注意:这是一种满足您的要求的方法,我不会建议它,因为它可能会惹恼用户。如果您希望用户完成您的表单,您可以使用正则表达式。]

不使用prompt,不。您必须使用现代技术,在页面顶部显示div或类似内容,并在其他地方禁用单击,并允许在调用它的代码中使用异步特性。您可以自己滚动,也可以使用为您做这件事的许多库中的任何一个。搜索"JavaScript模态对话框"可以找到大量的选择。

这里有一个使用Bootstrap的例子,但这只是许多可用选项之一:

$("#the-modal")
  .on("show.bs.modal", function() {
    // When the modal is about to be shown, clear the field
    $(this).find(".field").val("");
    $(this).find(".btn-primary").prop("disabled", true);
  })
  .on("shown.bs.modal", function() {
    // When the modal has been shown, focus the field
    $(this).find(".field").focus();
  })
  .on("hide.bs.modal", function() {
    // When the modal is closed, display the field's value
    display("Done, entered value: " + $(this).find("input").val());
  })
  .find(".field").on("keypress input paste change", function() {
    // When the field's value changes in any way, enable/disable
    // the 'Save Changes' button
    $("#the-modal .btn-primary").prop(
      "disabled",
      $.trim($(this).val()).length == 0
    );
  });
function display(msg) {
  $("<p>").html(String(msg)).appendTo(document.body);
}
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
  <meta charset="utf-8">
  <title>Example</title>
</head>
<body>
  <input type="button" value="Click me" data-toggle="modal" data-target="#the-modal">
  <div id="the-modal" class="modal fade" data-backdrop="static">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <label>Please provide the info:
          <input type="text" class="form-control field">
        </label>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal" disabled>Save Changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</body>
</html>

我非常怀疑您是否可以在内置警报、提示或确认警报中编辑浏览器。然而,你可以创建自己的弹出窗口,除非用户输入了什么,否则无法关闭。。。但即使这样,用户仍然可以编辑页面的HTML或禁用javascript。如果用户必须在无法关闭的情况下将某些内容输入框中,则应该包括某种服务器端检查。客户端浏览器中的任何内容都不会真正被关闭。