搜尋框、登入框常見需求:預設顯示提示圖示(如放大鏡、用戶圖標),使用者聚焦輸入時隱藏。本文提供原生 JS 與純 CSS 兩種方案,推薦零 JS 依賴的 CSS 實現。
<form id="search-form">
<input type="text" name="txtInput" />
<input type="submit" value="GO!" />
</form>
<script>
(function() {
var form = document.getElementById('search-form');
if (form && form.txtInput) {
var input = form.txtInput;
var unclicked = function() {
if (input.value === '') {
input.style.background = '#FFFFFF url(images/googbg.png) left no-repeat';
}
};
var clicked = function() {
input.style.background = '#ffffff';
};
input.onfocus = clicked;
input.onblur = unclicked;
unclicked(); // 初始化
}
})();
</script>
<style>
.search-input {
background: #fff url('images/googbg.png') left center no-repeat;
background-size: 20px 20px; /* 控制圖示大小 */
padding-left: 30px; /* 留出圖示空間 */
transition: background 0.2s ease; /* 平滑過渡 */
}
.search-input:focus {
background-image: none; /* 聚焦時移除背景圖 */
}
.search-input:not(:placeholder-shown) {
background-image: none; /* 有內容時也隱藏圖示 */
}
</style>
<input type="text" class="search-input" placeholder="搜尋..." />
優勢:
:placeholder-shown 偽類精準判斷「使用者已輸入內容」,比 value === '' 更語意化。<style>
.search-wrapper {
position: relative;
display: inline-block;
}
.search-wrapper::before {
content: '';
position: absolute;
left: 10px; top: 50%; transform: translateY(-50%);
width: 20px; height: 20px;
background: url('images/googbg.png') center/contain no-repeat;
pointer-events: none;
transition: opacity 0.2s;
}
.search-input {
padding-left: 40px;
background: transparent;
}
.search-input:focus + .search-wrapper::before,
.search-input:not(:placeholder-shown) + .search-wrapper::before {
opacity: 0;
}
</style>
<div class="search-wrapper">
<input type="text" class="search-input" placeholder="搜尋..." />
</div>
圖示與輸入框完全解耦,支援任意圖示、動畫、響應式佈局。
<label for="search" class="visually-hidden">搜尋</label>
<input type="text" id="search" class="search-input" placeholder="搜尋..." />
確保螢幕閱讀器可讀取標籤,placeholder 不替代 <label>。
**能用 CSS 解決的,絕不寫 JS。** 此場景純 CSS 方案在效能、維護性、無障礙、動畫流暢度全面優於 JS 版。現代前端開發應優先考慮 CSS 原生能力。