「點一下輸入框,裡面的提示文字就消失」是很早期的表單友善設計。做法是掛上 onfocus 把值清掉,再掛 onblur 在空白的時候把提示填回去,使用者就不会看到那句說明一直卡在已輸入的內容裡。
<input type="text" name="keyword" value="請輸入關鍵字"
onfocus="if(this.value=='請輸入關鍵字') this.value=''"
onblur="if(this.value=='') this.value='請輸入關鍵字'">
加上 if 判斷很重要,否則使用者好不容易打的字會在每次聚焦時被清掉。今天的 HTML5 已經有 placeholder 屬性能達到同樣效果,而且不會送出提示文字,優先使用它;上面這段仍有價值的地方在於它示範了 focus/blur 這對事件的搭配思路。
同一份素材裡還附了一個更有意思的練習——輸入「要幾個欄位」與「欄位類型」,就自動產生對應的 HTML。核心邏輯是一個迴圈加一段型別判斷:
function makeCode() {
var form = document.getElementsByTagName('form')[0];
var n = Number(form.elements[0].value); // 欄位數量
var type = form.elements[1].options[form.elements[1].selectedIndex].value;
var html = '<form>';
for (var i = 0; i < n; i++) {
if (type == 'radio' || type == 'checkbox') {
html += '<input type="' + type + '" name="' + type + '_' + n + '">' + type + '_' + i + ' ';
} else if (type == 'text') {
html += type + '_' + i + ': <input type="text" name="' + type + '_' + i + '"><br>';
} else {
html += '<input type="' + type + '" name="' + type + '_' + i + '"> ';
}
}
html += '</form>';
document.getElementById('code_value').value = html;
}
options[selectedIndex].value 是取得下拉選單目前選項的老派寫法,現在可以直接用 select.value。window.open() 的新視窗寫出,就能立刻看到成果,是很實用的除錯手法。若要繼續打磨,建議把字串拼接改成 document.createElement,並用 insertAdjacentHTML 取代 innerHTML 寫入,同時替每個欄位補上 label,鍵盤操作與閱讀器體驗都會好很多。