我的目标是换行提示。
Guess a number:
> __
//instead of
Guess a number: __
我正在寻找某种方法来执行此操作,在如下所示的提示中添加\ n会导致提示出现问题。
example = prompt("Guess a number \n >")
这可能吗?
prompt
输入区域的位置。但是您可以,如果您创建合适的模态。 (prompt
及其表亲无论如何都是用户不友好的-如果可能的话,最好避免使用它们)也许可以这样做:
const makePopup = (text, callback) => {
const modal = document.body.appendChild(document.createElement('div'));
modal.innerHTML = text + '<input style="margin-left: 20px">';
const input = modal.children[0];
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
modal.remove();
callback(input.value);
}
});
};
makePopup('foo', (value) => {
console.log('Got value', value);
});
如果您希望有多个弹出窗口,将它们设为基于Promise可能会更容易,然后您可以await
每个调用,以模拟prompt
的阻塞效果:const makePopup = (text) => { return new Promise((resolve) => { const modal = document.body.appendChild(document.createElement('div')); modal.innerHTML = text + '<input style="margin-left: 20px">'; const input = modal.children[0]; input.focus(); input.addEventListener('keypress', (e) => { if (e.key === 'Enter') { modal.remove(); resolve(input.value); } }); }); }; (async () => { const num = Math.floor(Math.random() * 5); let guessedNum; do { guessedNum = await makePopup('Guess a number 0-4'); } while (Number(guessedNum) !== num); console.log('You Win'); })();