Skip to content

ES6 - 对话框

JavaScript 在 Web 浏览器中运行时,可以利用内置的对话框与用户交互。这些对话框包括 alert()、confirm() 和 prompt()。虽然它们使用简单,但现代 Web 应用通常倾向于使用自定义模态对话框,以获得更好的用户体验和样式控制,因为这些原生对话框是阻塞的,可能会中断用户流程。

alert() 方法显示一个包含指定消息和“确定”按钮的模态对话框。它通常用于简单的通知或警告。

HTML 结构:
```html
<button id="showAlertBtn">Show Alert</button>
<p id="alertResult"></p>

JavaScript 代码:

function showAlert() {
alert("This is an alert message!");
// 用户点击“确定”后,这里的代码会执行。
document.getElementById('alertResult').textContent = 'Alert was shown and dismissed.';
}
// 最好使用 JavaScript 附加事件监听器
document.getElementById('showAlertBtn').addEventListener('click', showAlert);
当点击“显示警告框”按钮时,会弹出一个对话框,显示文本“This is an alert message!”和一个“确定”按钮。脚本执行会暂停,直到用户关闭警告框。关闭后,ID 为 `alertResult` 的段落会更新。
## 确认框 (`confirm()`)
`confirm()` 方法显示一个包含指定消息以及“确定”和“取消”两个按钮的对话框。它用于获取用户的布尔类型确认。
如果用户点击“确定”,`confirm()` 返回 `true`;如果用户点击“取消”或关闭对话框,则返回 `false`。
### 示例:
```javascript
HTML 结构:
```html
<button id="showConfirmBtn">Show Confirmation</button>
<p id="confirmResult"></p>

JavaScript 代码:

function getConfirmation() {
const userResponse = confirm("Do you want to proceed?");
const resultParagraph = document.getElementById('confirmResult');
if (userResponse) {
resultParagraph.textContent = "User chose to proceed (OK).";
} else {
resultParagraph.textContent = "User chose not to proceed (Cancel).";
}
}
document.getElementById('showConfirmBtn').addEventListener('click', getConfirmation);
点击“显示确认框”按钮将显示一个对话框,询问“Do you want to proceed?”,并带有“确定”和“取消”按钮。`confirmResult` 段落中的文本将根据用户的选择进行更新。
## 提示输入框 (`prompt()`)
`prompt()` 方法显示一个对话框,提示用户输入。它包含一条消息、一个文本输入字段以及“确定”/“取消”按钮。
`prompt()` 接受两个可选参数:`message`(显示给用户的文本)和 `defaultText`(在输入字段中默认显示的字符串)。如果用户点击“确定”,它返回用户输入的字符串;如果用户点击“取消”或关闭对话框,则返回 `null`。如果用户点击“确定”但未输入文本,则返回空字符串。
### 示例:
```css
HTML 结构:
```html
<button id="showPromptBtn">Get User Input</button>
<p id="promptResult"></p>

JavaScript 代码:

function getUserInput() {
const userName = prompt("Please enter your name:", "Guest User");
const resultParagraph = document.getElementById('promptResult');
if (userName === null) {
resultParagraph.textContent = "User cancelled the prompt.";
} else if (userName === "") {
resultParagraph.textContent = "User entered an empty name.";
} else {
resultParagraph.textContent = `Welcome, ${userName}!`;
}
}
document.getElementById('showPromptBtn').addEventListener('click', getUserInput);
点击“获取用户输入”将显示一个对话框,询问用户的姓名,输入字段中默认显示“Guest User”。`promptResult` 段落将根据用户输入的内容或用户是否取消来显示消息。
### 现代 Web 开发的考量:
- 用户体验:原生对话框是同步的(阻塞的),这意味着它们会暂停脚本执行,并且可能感觉具有侵扰性。现代 UI 通常使用异步、非阻塞的自定义模态框或通知,它们能更好地与页面集成。
- 样式控制:原生对话框无法使用 CSS 进行样式设置,导致在不同浏览器和平台上的样式不一致。
- 功能性:与使用 HTML、CSS 和 JavaScript 构建的自定义解决方案相比,它们提供的功能有限。
- 可访问性:虽然浏览器供应商致力于使原生对话框具有可访问性,但自定义解决方案提供了更多控制,以确保完全兼容 ARIA 规范和支持键盘导航。
为了创建更丰富、集成度更高的用户交互,可以探索构建自定义 UI 组件或使用像 Bootstrap Modals、Material UI Dialogs 等库。