搜索框是幾乎每個網站都有的元件,但預設樣式實在稱不上好看。下面這個範例只用 CSS,就能做出帶有 hover 換色、focus 態的簡約搜尋框。
效果如下:
也可以點這裡查看效果:https:///keleyi/phtml/divcss/8.htm
<html>
<head>
<title>搜索框的實現</title>
<meta charset="UTF-8">
<style type="text/css">
body { font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:14px; }
h1 { margin-top:0px; margin-bottom:8px; }
a { text-decoration:none; color:#1c00ff; }
a:hover { color:#5f00e4; }
fieldset.search_keleyi_com { padding: 0px; border: none; width: 232px; background:#e0e0e0; }
fieldset.search_keleyi_com:hover { background: #a8a8a8; }
.search_keleyi_com input, .search_keleyi_com button { border: none; float: left; }
.search_keleyi_com input.box_keleyi_com { height: 28px; width: 200px; margin: 1px; background: #e0e0e0; padding-right: 0px; }
.search_keleyi_com input.box_keleyi_com:focus { background: #e8e8e8; outline: none; }
.search_keleyi_com button.btn_keleyi_com { border: none; width: 28px; height: 28px; margin: 1px; background: url(https:///keleyi/phtml/divcss/8/search_blue.png) no-repeat top right; }
.search_keleyi_com button.btn_keleyi_com:hover { background: url(https:///keleyi/phtml/divcss/8/search_black.png) no-repeat bottom right; }
</style>
</head>
<body>
<div>
<h2>搜索框</h2>
<form method="get" id="searchform" action="https:///">
<fieldset class="search_keleyi_com">
<input type="text" class="box_keleyi_com inputText_keleyi_com" name="s" id="s" placeholder="輸入關鍵字" x-webkit-speech>
<button class="btn_keleyi_com" title="search_keleyi_com"> </button>
</fieldset>
</form>
</div>
</body>
</html>
用 fieldset 當外框、把 border 拿掉,是為了保留它語義上的「表單群組」意義,同時視覺上完全可控。
輸入框與按鈕都用 float:left 並排,靠 margin:1px 留出細窄的間隙,讓兩者看起來像一個整體卻又有層次。
按鈕的 hover 效果是切換背景圖並改變 background-position(top right 對 bottom right),這種「同一張圖上下拼接、用位移切換」的做法,可以省下額外的圖片請求。
placeholder 屬性提供輸入提示,x-webkit-speech 則是早期 Chrome 的語音輸入實驗屬性,不支援的瀏覽器會直接忽略,不影響功能。