萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

HTML Input 文本框三合一:垂直居中、灰色佔位符、點擊清空完美實現

輸入框交互三重奏:垂直居中 + 佔位符 + 聚焦清空

單行文本框常見交互需求:內容垂直居中、灰色提示文字、點擊聚焦時清空提示、失焦無內容時恢復。單行代碼實現三合一,但存在維護性與可用性問題。

原版一行代碼

<input type="text" name="wd1" id="qy_1" maxlength="100" 
  style="color:gray;width:199px;height:30px;line-height:30px;" 
  autocomplete="off" value="請輸入企業名稱" 
  onfocus="javascript:if(this.value == '請輸入企業名稱') this.value = ''; this.style.color='gray';" 
  onblur="if(this.value == '') {this.value = '請輸入企業名稱'; this.style.color = 'gray';}">

技術細節拆解

需求實現方式問題
垂直居中height:30px; line-height:30px固定高度,內容超出不換行,不同字體基線可能偏移
灰色提示color:gray + value="提示文字"真實值與提示值混淆,提交表單會發送提示文字
聚焦清空onfocus 判斷值等於提示則清空用戶輸入恰好等於提示文字時會被誤清空
失焦恢復onblur 判斷空值則恢復同上,且 style.color='gray' 重複設置

HTML5 原生 placeholder 完美替代 (推薦)

<input type="text" name="wd1" id="qy_1" maxlength="100" 
  placeholder="請輸入企業名稱" 
  style="width:199px; height:30px; line-height:30px; padding:0 10px;"
  autocomplete="off">

<style>
/* placeholder 樣式自定義 */
::placeholder { color: #999; opacity: 1; } /* Firefox 需 opacity:1 */
::-webkit-input-placeholder { color: #999; }
::-moz-placeholder { color: #999; opacity: 1; }
:-ms-input-placeholder { color: #999; } /* IE10-11 */
</style>

優勢對比

  • 語義正確:placeholder 明確標識提示文本,不會隨表單提交
  • 無 JS 依賴:純 CSS/HTML 實現,無腳本錯誤風險
  • 可訪問性:屏幕閱讀器正確識別,label 關聯更佳
  • 垂直居中更穩健:配合 padding + box-sizing:border-box

垂直居中最佳實踐 (現代 CSS)

.input-field {
  width: 100%;
  max-width: 300px;
  height: 40px;
  padding: 0 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
  box-sizing: border-box; /* 關鍵:padding 計入 width/height */
  /* 垂直居中三重保障 */
  display: flex;
  align-items: center;
  /* 或單純依賴 line-height = height (單行文本) */
}

進階:浮動標籤模式

<div class="float-label">
  <input type="text" id="company" placeholder=" "> <!-- 空格佔位觸發浮動 -->
  <label for="company">請輸入企業名稱</label>
</div>

<style>
.float-label { position: relative; width: 300px; }
.float-label input { width: 100%; height: 44px; padding: 12px 0 4px; border: none; border-bottom: 1px solid #ccc; background: transparent; }
.float-label label { position: absolute; left: 0; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none; transition: all 0.2s; }
.float-label input:focus + label,
.float-label input:not(:placeholder-shown) + label { top: 0; transform: translateY(-100%); font-size: 12px; color: #007bff; }
</style>
copyright © 萬盛學電腦網 all rights reserved