有限版面空間下,搜尋欄平時收縮為圖示,點擊展開輸入框,兼顧美觀與功能。結合 CSS3 Transition 與 jQuery 實現平滑動畫與狀態切換。
<div id="search_bar" class="search_bar">
<form id="myform">
<input class="input" placeholder="想搜點什麼呢..." type="text" name="key" id="search">
<input class="search_btn" type="submit" value="">
<span class="search_ico"></span>
</form>
</div>
.search_bar {
position: relative; float: right;
width: 0; min-width: 60px; height: 60px;
overflow: hidden;
background: #162934;
transition: width 0.3s ease; /* 核心動畫 */
-webkit-transition: width 0.3s ease;
-webkit-backface-visibility: hidden; /* 修正 Chrome 閃爍 */
}
.input {
position: absolute; top: 0; right: 0;
width: 98%; height: 60px; line-height: 60px;
border: none; outline: none;
font-size: 20px; color: #f9f9f9; background: transparent;
z-index: 10;
}
.search_ico, .search_btn {
position: absolute; right: 0; top: 0;
width: 60px; height: 60px; line-height: 60px;
cursor: pointer; padding: 0; margin: 0;
}
.search_ico { background: #e67e22 url(icon.png) no-repeat 18px 20px; z-index: 90; }
.search_open { width: 100% !important; z-index: 1002; } /* 展開狀態 */
$(function() {
$('.search_ico').click(function() {
$('.search_bar').toggleClass('search_open');
var keys = $('#search').val();
if (keys.length > 2) {
$('#search').val('');
$('#myform').submit();
} else {
return false; // 輸入過短不提交,保持展開
}
});
});
width:0 → 100% 配合 transition 產生寬度動畫,min-width:60px 保留圖示可見區。overflow:hidden 裁切收縮時的輸入框。z-index 層級管理:圖示 90、輸入框 10、展開態容器 1002 置頂。backface-visibility:hidden 修正 WebKit 3D 加速閃爍。<label for="search" class="sr-only">搜尋關鍵字</label>
<input ... id="search" aria-label="搜尋關鍵字">
.search_ico { role="button"; tabindex="0"; aria-label="展開搜尋"; }
鍵盤可聚焦圖示、Enter/Space 觸發展開、螢幕閱讀器可讀。