[英]input field always prompts for input rather than showing placeholder text
我有一個input
框,用戶可以input
:
<input id="entry" type="text" onkeypress="BeginTest(event)" placeholder="To start the test, begin typing here." class="focus">
並且在此輸入框中,他們鍵入的所有內容都將存儲在變量中,但是當它們敲入空格或回車時將被清除。
var entry = document.getElementById("entry");
function BeginTest(event) {
if (event.which == 32 || event.which == 13) {
//store entry.value or do whatever
entry.value = "";
}
}
問題是當他們在輸入框中輸入新內容時,輸入之前輸入框已經是空格。 所以,如果我執行:
然后,我現在必須單擊一個退格鍵才能看到其中的entry.placeholder文本。 每當按下空格或Enter鍵時,如何使它不包括該空格?
這也很煩人,因為我當前必須使用entry.value.trim()
刪除開始的空格。
捕獲keyup
而不是keypress
,然后確保取消對擊鍵的處理,因此在處理程序完成之后,不會將其添加到空值中。
var entry = document.getElementById("entry"); function BeginTest(event) { if (event.which == 32 || event.which == 13) { entry.value = ""; event.stopPropagation(); event.preventDefault(); return false; } }
<input id="entry" type="text" onkeyup="BeginTest(event)" placeholder="To start the test, begin typing here." class="focus">
出現空格是因為在調用事件偵聽器之前,字符不會添加到輸入的值中。 如果要取消事件,則不會添加角色。
event.preventDefault();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.