萬盛學電腦網

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

jQuery 文字框焦點獲得/失去事件與預設值提示實作

版本一:基本焦點樣式切換

.focus {
    border: 1px solid #f00;
    background: #fcc;
}

$(function() {
    $(":input").focus(function() {
        $(this).addClass("focus");
    }).blur(function() {
        $(this).removeClass("focus");
    });
});
  • :input 選擇器匹配所有 input, textarea, select, button
  • focus() / blur() 綁定獲得/失去焦點事件
  • $(this) 自動指向觸發事件的元素

版本二:預設提示文字(Placeholder 效果)

$(function() {
    $(":input").focus(function() {
        $(this).addClass("focus");
        if ($(this).val() === this.defaultValue) {
            $(this).val("").removeClass("focus"); // 清空並移除提示樣式
        }
    }).blur(function() {
        $(this).removeClass("focus");
        if ($(this).val() === "") {
            $(this).val(this.defaultValue).addClass("focus"); // 還原提示
        }
    });
});

HTML 範例

<form id="regForm">
    <div><label for="username">名稱:</label>
        <input id="username" type="text" value="請輸入名稱" /></div>
    <div><label for="pass">密碼:</label>
        <input id="pass" type="password" value="請輸入密碼" /></div>
    <div><label for="msg">詳細信息:</label>
        <textarea id="msg" rows="2" cols="20">請輸入詳細資訊</textarea></div>
</form>

現代最佳實踐

<!-- HTML5 原生 placeholder,無需 JS -->
<input type="text" placeholder="請輸入名稱" />
<textarea placeholder="請輸入詳細資訊"></textarea>
  • 原生 placeholder:無需 JS、語意正確、無障礙友善、不會隨表單送出
  • 舊瀏覽器(IE9-)才需 JS 模擬
  • CSS 樣式控制:::placeholder { color: #999; }
copyright © 萬盛學電腦網 all rights reserved