搜尋框在未輸入時顯示一行灰字提示,點進去後文字消失、顏色轉深,離開時若仍空白則恢復提示——這是常見的表單引導手法。本文示範如何用 jQuery 實作,並示範一個容易踩到的樣式覆蓋問題該怎麼解決。
<html>
<head>
<title>jquery:搜尋框效果</title>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(function(){
$('#search').val("請輸入搜尋內容").addClass("c1");
$('#search').focus(function(){ // 搜尋框獲得焦點時
$('#search').val("").addClass("c2");
});
$('#search').blur(function(){ // 搜尋框失去焦點時
if($('#search').val()==""){
$('#search').val("請輸入搜尋內容").attr("class","c1");
}
});
});
</script>
<style type="text/css">
.c1{color:gray;font-style:italic;}
.c2{color:#000;font-style:normal;}
</style>
</head>
<body>
<input type="text" size="38" id="search" /><button>搜尋</button>
</body>
</html>
第一,用 attr("class", "c1") 是「設定」而非「追加」,如果這個輸入框原本還掛著其他 class,失去焦點後那些樣式會一起消失。
第二,改用 addClass() 雖然不會洗掉其他樣式,但原本的 c2 並沒有被移除,只是靠 CSS 的後定義優先規則蓋掉——這需要 c1 寫在 c2 之後才會生效,顯得很脆弱。jQuery 並沒有提供「直接替換 class」的單一方法。
思路很簡單:加上新樣式的同時,把舊樣式摘掉。另外焦點事件裡也該多一層判斷,避免使用者真的想輸入「請輸入搜尋內容」這幾個字時被清掉。
<html>
<head>
<title>jquery:搜尋框效果</title>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(function(){
$('#search').val("請輸入搜尋內容").addClass("c1");
$('#search').focus(function(){ // 獲得焦點
if($('#search').val()=="請輸入搜尋內容"){
$('#search').val("").addClass("c2").removeClass("c1");
}
});
$('#search').blur(function(){ // 失去焦點
if($('#search').val()==""){
$('#search').val("請輸入搜尋內容").addClass("c1").removeClass("c2");
}
});
});
</script>
<style type="text/css">
.c1{color:gray;font-style:italic;}
.c2{color:#000;font-style:normal;}
</style>
</head>
<body>
<input type="text" size="38" id="search" /><button>搜尋</button>
</body>
</html>
這段邏輯靠 jQuery 的鏈式呼叫串起來,可讀性不錯。若用 HTML5,直接寫 <input placeholder="請輸入搜尋內容"> 就能交給瀏覽器處理,程式碼少很多;但在需要相容舊版瀏覽器的專案裡,上面這種手寫方案仍然派得上用場。