DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
點擊輸入框就清空:提示文字技巧與表單自動生成
編輯:CSS詳解     

「點一下輸入框,裡面的提示文字就消失」是很早期的表單友善設計。做法是掛上 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 + '">&nbsp;';
    }
  }

  html += '</form>';
  document.getElementById('code_value').value = html;
}

這段程式值得學的地方

  • name 的命名規則:radio 同組必須共用一個 name 才能互斥,所以用的是「型別_組別」;checkbox 則每個都要獨立名稱,兩者刻意不同。
  • readOnly 的取法:options[selectedIndex].value 是取得下拉選單目前選項的老派寫法,現在可以直接用 select.value。
  • 預覽:把字串丟進 window.open() 的新視窗寫出,就能立刻看到成果,是很實用的除錯手法。

若要繼續打磨,建議把字串拼接改成 document.createElement,並用 insertAdjacentHTML 取代 innerHTML 寫入,同時替每個欄位補上 label,鍵盤操作與閱讀器體驗都會好很多。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved