简体   繁体   English

如何自定义Javascript的Confirm()框

[英]How to customize the Javascript's confirm() box

How does stackoverflow customize the confirm() box's buttons and add custom text to the buttons? stackoverflow如何自定义confirm()框的按钮并将自定义文本添加到按钮?

在此处输入图片说明

All the other questions I looked at pointed at a random jQuery plugin to do this. 我看过的所有其他问题都指向一个随机的jQuery插件来完成。 Can this be done with Vanilla Javascript? 可以使用Vanilla Javascript完成吗? If yes, then how? 如果是,那怎么办?

There are only specific messages/buttons you can offer the user, without using a custom alert box/plugin. 您可以为用户提供特定的消息/按钮,而无需使用自定义警报框/插件。 They are: 他们是:

  1. To display a message with just an OK button, by calling: 要仅通过“ 确定”按钮显示消息,请调用:

     window.alert('Message'); 
  2. To display a message with OK / Cancel as the options, by calling: 要显示以“ 确定” /“ 取消”为选项的消息,请调用:

     var didTheyPressOK = window.confirm('Are you sure you want to XXXXX?'); 
  3. As StackOverflow does in your example , to display a Leave... / Stay... message on leaving the page, where pressing Stay causes the browser to stay on your page (the exact button wording is browser-dependent, you cannot control it): 就像您的示例中的StackOverflow一样,在离开页面时显示“ Leave ... / Stay ...”消息,按“ Stay”将使浏览器停留在页面上(确切的按钮文字取决于浏览器,您无法控制它):

     window.onbeforeunload = function() { // you may or may not want a condition here, eg // if (thereAreUnsavedChanges) return 'Are you sure you actually want to leave? You have unsaved changes...'; } 

For any other situation, you'll need to use some kind of alert plugin (or write one yourself :-/), as you speculated in your question. 对于任何其他情况,您都需要使用某种警报插件(或者自己写一个:-/),就像您在问题中所推测的那样。


Put simply, those buttons are browser specific and chrome automatically displays helpful text on the button to make things clearer. 简而言之,这些按钮是特定于浏览器的,Chrome会在该按钮上自动显示有用的文本,以使内容更清晰。 It happens with window.onbeforeunload if you return a string, which is displayed as a message before navigation. 如果您返回一个字符串,则会在window.onbeforeunload发生,该字符串在导航之前显示为消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM