JavaScript中的prompt
函数用于显示一个对话框,提示用户输入一些文本。这个对话框默认情况下具有浏览器的原生样式,通常无法直接通过CSS来修改其外观。不过,可以通过一些变通的方法来实现样式的自定义。
prompt
函数的基本语法如下:
let userInput = prompt(message, defaultValue);
message
:显示给用户的提示信息。defaultValue
:可选参数,作为输入框的默认值。由于prompt
对话框的样式是由浏览器控制的,我们不能直接修改它的CSS。但是,可以使用HTML、CSS和JavaScript创建一个自定义的模态对话框(modal),以实现样式的自定义。
以下是一个简单的自定义模态对话框的实现:
HTML:
<div id="customPrompt" class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<p id="promptMessage">请输入一些文本:</p>
<input type="text" id="promptInput">
<button id="promptSubmit">提交</button>
</div>
</div>
CSS:
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close-button {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close-button:hover,
.close-button:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
JavaScript:
function customPrompt(message, defaultValue) {
document.getElementById('promptMessage').textContent = message;
document.getElementById('promptInput').value = defaultValue || '';
document.getElementById('customPrompt').style.display = 'block';
return new Promise((resolve) => {
document.getElementById('promptSubmit').onclick = function() {
document.getElementById('customPrompt').style.display = 'none';
resolve(document.getElementById('promptInput').value);
};
document.getElementsByClassName('close-button')[0].onclick = function() {
document.getElementById('customPrompt').style.display = 'none';
resolve(null);
};
});
}
// 使用自定义的prompt
customPrompt('请输入你的名字:', '').then((name) => {
console.log('用户输入的名字:', name);
});
通过上述方法,你可以创建一个具有自定义样式的模态对话框,以替代原生的prompt
函数。
领取专属 10元无门槛券
手把手带您无忧上云