<script>
$(function() {
$('#search').val("請輸入搜尋內容").addClass("c1"); // 初始化
$('#search').focus(function() {
$('#search').val("").addClass("c2"); // 清空 + 加入正常樣式
});
$('#search').blur(function() {
if ($('#search').val() === "") {
$('#search').val("請輸入搜尋內容").attr("class", "c1"); // 直接設 class,覆蓋 c2
}
});
});
</script>
<style>
.c1 { color: gray; font-style: italic; }
.c2 { color: #000; font-style: normal; }
</style>
⚠️ **問題**:`attr("class", "c1")` 會移除所有其他 class,若輸入框原本有 `form-control` 等樣式類別會遺失。
<script>
$(function() {
var $search = $('#search');
var placeholder = "請輸入搜尋內容";
$search.val(placeholder).addClass("placeholder");
$search.focus(function() {
if ($search.val() === placeholder) {
$search.val("").removeClass("placeholder").addClass("active");
}
});
$search.blur(function() {
if ($search.val() === "") {
$search.val(placeholder).removeClass("active").addClass("placeholder");
}
});
});
</script>
<style>
.placeholder { color: #999; font-style: italic; }
.active { color: #000; font-style: normal; }
/* 原本樣式保留 */
.form-control { padding: 8px 12px; border: 1px solid #ccc; border-radius: 4px; }
</style>
<input type="search" id="search" placeholder="請輸入搜尋內容" class="form-control">
<style>
/* 自訂 placeholder 顏色 */
::-webkit-input-placeholder { color: #999; font-style: italic; }
:-moz-placeholder { color: #999; font-style: italic; }
::-moz-placeholder { color: #999; font-style: italic; }
:-ms-input-placeholder { color: #999; font-style: italic; }
</style>
✅ **優點**:原生實作、無 JS 依賴、無障礙支援佳、不會干擾表單提交值。
⚠️ **缺點**:IE9 以下不支援;無法在 `focus` 時強制清空 (原生行為是輸入時才隱藏)。
$search.on('compositionstart', function() { this.dataset.composing = true; })
.on('compositionend', function() {
this.dataset.composing = false;
if (!this.value.trim()) {
$(this).val(placeholder).addClass('placeholder').removeClass('active');
}
});
$.fn.searchBox = function(options) {
var opts = $.extend({
placeholder: '請輸入搜尋關鍵字',
placeholderClass: 'search-placeholder',
activeClass: 'search-active',
onSearch: null // function(query)
}, options);
return this.each(function() {
var $input = $(this);
$input.attr('placeholder', opts.placeholder) // 原生支援
.addClass(opts.placeholderClass)
.on('focus', function() { $(this).removeClass(opts.placeholderClass).addClass(opts.activeClass); })
.on('blur', function() { if (!this.value) $(this).removeClass(opts.activeClass).addClass(opts.placeholderClass); })
.on('keydown', function(e) { if (e.key === 'Enter' && opts.onSearch) opts.onSearch(this.value.trim()); });
});
};
// 使用
$('#search').searchBox({
placeholder: '搜尋商品、品牌...',
onSearch: function(q) { location.href = '/search?q=' + encodeURIComponent(q); }
});