提示中的新行
New Line in a prompt
我的目标是换行提示。
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');
})();
我的目标是换行提示。
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');
})();