搜索框 `blur` 事件恢復佔位文本時,文本位置跳動是經典前端坑。根因:輸入框無固定尺寸,內容變化觸發回流重排。解決極簡——**給輸入框鎖定寬高**。
// 搜索框交互邏輯
$("#txtSearch").focus(function() {
if ($(this).val() === "請輸入搜索關鍵字") {
$(this).val("").css("color", "black");
}
}).blur(function() {
if ($(this).val() === "") {
$(this).css("color", "gray").val("請輸入搜索關鍵字");
}
});
#txtSearch {
width: 480px; /* 固定寬度 */
height: 20px; /* 固定高度 */
vertical-align: middle; /* 垂直居中對齊 */
}
通用原則:所有動態切換文本的輸入框/按鈕/標籤,**務必預設固定尺寸**,是防跳動、防佈局抖動的基礎工程規範。