萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實作搜尋框預設提示文字:focus/blur 狀態切換

需求分析

  • 初始顯示灰色提示文字:「請輸入搜尋內容」
  • 獲得焦點:清空提示、切換為黑色正常輸入樣式
  • 失去焦點:若為空,恢復提示文字與灰色樣式
  • 若使用者輸入了內容再清空 → 仍視為空,恢復提示

基礎版 (有殘留 class 問題)

<script>
$(function() {
  $('#search').val("請輸入搜尋內容").addClass("c1"); // 初始化

  $('#search').focus(function() {
    $('#search').val("").addClass("c2"); // 清空 + 加入正常樣式
  });

  $('#search').blur(function() {
    if ($('#search').val() === "") {
      $('#search').val("請輸入搜尋內容").attr("class", "c1"); // 直接設 class,覆蓋 c2
    }
  });
});
</script>
<style>
.c1 { color: gray; font-style: italic; }
.c2 { color: #000; font-style: normal; }
</style>

⚠️ **問題**:`attr("class", "c1")` 會移除所有其他 class,若輸入框原本有 `form-control` 等樣式類別會遺失。

改良版:addClass/removeClass 管理狀態

<script>
$(function() {
  var $search = $('#search');
  var placeholder = "請輸入搜尋內容";

  $search.val(placeholder).addClass("placeholder");

  $search.focus(function() {
    if ($search.val() === placeholder) {
      $search.val("").removeClass("placeholder").addClass("active");
    }
  });

  $search.blur(function() {
    if ($search.val() === "") {
      $search.val(placeholder).removeClass("active").addClass("placeholder");
    }
  });
});
</script>
<style>
.placeholder { color: #999; font-style: italic; }
.active { color: #000; font-style: normal; }
/* 原本樣式保留 */
.form-control { padding: 8px 12px; border: 1px solid #ccc; border-radius: 4px; }
</style>

現代最佳實踐:HTML5 `placeholder` 屬性 (零 JS)

<input type="search" id="search" placeholder="請輸入搜尋內容" class="form-control">

<style>
/* 自訂 placeholder 顏色 */
::-webkit-input-placeholder { color: #999; font-style: italic; }
:-moz-placeholder { color: #999; font-style: italic; }
::-moz-placeholder { color: #999; font-style: italic; }
:-ms-input-placeholder { color: #999; font-style: italic; }
</style>

✅ **優點**:原生實作、無 JS 依賴、無障礙支援佳、不會干擾表單提交值。
⚠️ **缺點**:IE9 以下不支援;無法在 `focus` 時強制清空 (原生行為是輸入時才隱藏)。

進階:支援輸入法組合事件

$search.on('compositionstart', function() { this.dataset.composing = true; })
       .on('compositionend', function() {
         this.dataset.composing = false;
         if (!this.value.trim()) {
           $(this).val(placeholder).addClass('placeholder').removeClass('active');
         }
       });

完整生產級元件封裝

$.fn.searchBox = function(options) {
  var opts = $.extend({
    placeholder: '請輸入搜尋關鍵字',
    placeholderClass: 'search-placeholder',
    activeClass: 'search-active',
    onSearch: null // function(query)
  }, options);

  return this.each(function() {
    var $input = $(this);
    $input.attr('placeholder', opts.placeholder) // 原生支援
          .addClass(opts.placeholderClass)
          .on('focus', function() { $(this).removeClass(opts.placeholderClass).addClass(opts.activeClass); })
          .on('blur', function() { if (!this.value) $(this).removeClass(opts.activeClass).addClass(opts.placeholderClass); })
          .on('keydown', function(e) { if (e.key === 'Enter' && opts.onSearch) opts.onSearch(this.value.trim()); });
  });
};

// 使用
$('#search').searchBox({
  placeholder: '搜尋商品、品牌...',
  onSearch: function(q) { location.href = '/search?q=' + encodeURIComponent(q); }
});

總結建議

  1. **現代專案優先使用 HTML5 `placeholder`** + CSS 樣式化,最簡潔、效能最好。
  2. 需支援 IE9- 或需「焦點即清空」行為時,使用 **改良版 JS 方案** (addClass/removeClass 管理狀態)。
  3. 避免使用 `attr('class', ...)` 覆蓋整個 class 屬性,破壞現有樣式。
  4. 封裝為 jQuery Plugin 可複用,保持 HTML 語意乾淨。
copyright © 萬盛學電腦網 all rights reserved