相信大家都用過淘寶那種可以切換搜尋類別的搜尋框——想搜商品就切到「商品」,想搜賣場就切到「店鋪」,切換時提示文字也會跟著改變。這種互動其實不難,下面就用 HTML、CSS 搭配少許 jQuery 來還原它。
效果預覽:

首先是 HTML 結構,用 ul 做標籤頁,每個 li 帶一個 tips 屬性存放該分類的提示文字:
<div class="search"> <div id="searchBox"> <ul class="tab-bar clearfix" id="tabBar"> <li class="current" tips="請輸入產品名稱">商品</li> <li class="tab-line"><span>|</span></li> <li tips="請輸入店鋪名稱">店鋪</li> </ul> <div class="tab-box clearfix" id="tabBox"> <form onsubmit="" action="" method="get" name="searchForm" id="searchForm" class="clearfix"> <input class="text" id="keyword" name="keyword" lang="zh-CN" type="text" value="請輸入產品名稱"> <input class="button" value="搜索" onfocus="this.blur()" type="submit"> </form> </div> </div> <div class="keyword"> <a href="#"><span>男裝</span></a> <a href="#"> 朵牧女鞋</a> <a href="#">聖高男鞋</a> <a href="#"><span>女裝</span></a> <a href="#">防曬霜</a> <a href="#">脫毛膏</a> </div> </div>
接著是 CSS,負責排版與切換時的高亮樣式:
.search{ position: absolute; top:14px; left: 34%; width:477px; _width:477px; height: 81px;} .keyword a{ font-size: 12px; line-height: 18px; color:#999; padding:0 4px;} .keyword a span{ color:#fb5004;} .tab-bar li.current{ color: #1d7ad9; font-weight: bold; background: url(../images/trian_up.png) no-repeat center bottom; padding-bottom: 9px;} .tab-bar li{ width:38px; text-align: center; color: #444; float: left; cursor: pointer;} .tab-bar li.tab-line{ width: 2px; color: #c9c9c9; margin:0 2px;} .tab-box{ border:2px solid #1d7ad9;} .text{ color: #a9a9a9; width:376px; height: 31px; border:none; text-indent: 10px; float:left; outline: none; border:0;} .button{ width: 97px; height: 32px; text-align: center; color: #fff; font-size:18px; background: #1d7ad9; border:none; float: left;}最後是 JavaScript,透過事件委派監聽 li 的點擊,切換 current 樣式並更新輸入框的提示文字:
<script type="text/javascript"> $(function(){ // 搜索切換 $('#tabBar').on('click', 'li', function(){ var tips = $(this).attr('tips'); if(tips){ $(this).addClass('current').siblings().removeClass('current'); $('#keyword').val(tips); } }); }); </script>這裡有個小細節:分隔用的 li.tab-line 因為沒有 tips 屬性,點它時 if(tips) 判斷會失敗,所以不會觸發切換,正好達到了「點分隔線沒反應」的效果。透過這種把資料存在自訂屬性、再用事件委派處理的寫法,整個元件既輕量又好維護。