prompt实现js
使用 JavaScript 实现 Prompt
在 JavaScript 中,prompt 是一个内置函数,用于显示一个对话框,提示用户输入文本。以下是如何使用 prompt 的基本方法:
let userInput = prompt("请输入您的姓名:");
console.log("用户输入的内容是:" + userInput);
自定义 Prompt 样式
默认的 prompt 对话框样式由浏览器决定,无法直接修改。如果需要自定义样式,可以通过 HTML 和 CSS 创建一个模态框:

<div id="customPrompt" style="display: none;">
<div class="prompt-content">
<p>请输入您的姓名:</p>
<input type="text" id="userInput">
<button onclick="submitPrompt()">提交</button>
</div>
</div>
<script>
function showCustomPrompt() {
document.getElementById("customPrompt").style.display = "block";
}
function submitPrompt() {
let userInput = document.getElementById("userInput").value;
console.log("用户输入的内容是:" + userInput);
document.getElementById("customPrompt").style.display = "none";
}
</script>
验证用户输入
在使用 prompt 时,可以验证用户输入是否为空或是否符合要求:

let userInput = prompt("请输入您的年龄:");
if (userInput === null || userInput === "") {
alert("输入不能为空!");
} else if (isNaN(userInput)) {
alert("请输入有效的数字!");
} else {
console.log("您的年龄是:" + userInput);
}
结合 Promise 使用
为了更灵活地处理用户输入,可以将 prompt 封装在一个 Promise 中:
function showPrompt(message) {
return new Promise((resolve) => {
let userInput = prompt(message);
resolve(userInput);
});
}
showPrompt("请输入您的邮箱:")
.then(input => {
if (input) {
console.log("邮箱地址是:" + input);
} else {
console.log("未输入任何内容");
}
});
使用第三方库
如果需要更高级的功能,可以使用第三方库如 SweetAlert 来实现美观的提示框:
// 引入 SweetAlert 库后使用
Swal.fire({
title: '请输入您的姓名',
input: 'text',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: '提交',
cancelButtonText: '取消'
}).then((result) => {
if (result.isConfirmed) {
console.log("用户输入的内容是:" + result.value);
}
});
以上方法涵盖了从基础到高级的 prompt 实现方式,可以根据需求选择适合的方案。






