css 實現 focus 時 placeholder 文字會顯示到邊框上方的效果
阿新 • • 發佈:2022-03-24
實現一個輸入框 focus
狀態下,placeholder 文字會顯示到邊框上方,且輸入框有文字時會停留在上方的效果,如下圖:
原始碼見 倉庫地址
思路1:用消失/顯示效果
使用 input
自帶的 placeholder
屬性。
非 focus 時:顯示 placeholder
屬性中的文字
focus 時:隱藏placeholder
屬性的文字,顯示輸入框頂部的絕對定位的文字。
實現了一下效果不好,第 2 種用動畫的思路更好。
思路2:用動畫
html:
<div class="input-wrapper"> <input type="email" class="text-input email" placeholder=" "> <label class="input-label">Email</label> </div>
思路:
- 將表單的
<label>
標籤用作 placeholder,將<input>
自帶的 placeholder 屬性值設為一個空格。 -
<input>
與<label>
皆相對容器絕對定位 -
<input>
focus 時,修改<label>
的top
與left
屬性改變其位置 - 輸入框有文字時,使
<label>
維持 3 中的狀態。
1-3 使用絕對定位。問題在第4點,css 中如果獲取輸入框文字,且沒有 focus 的狀態?
換一種角度:獲取沒有 placeholder 且沒有 focus 的狀態,這是將 <input>
placeholder
屬性值設為一個空格的原因:
/* placeholder 沒有顯示狀態下,且沒有focus的 text-input 的相鄰兄弟選擇器 input-label */
.text-input:not(:placeholder-shown).text-input:not(:focus) + .input-label {
}
完整 css:
.input-wrapper { position: relative; } .text-input { border: 1px solid #ddd; border-radius: 6px; padding: 10px; outline: none; position: absolute; background-color: transparent; z-index: 1; } .text-input:focus { border: 1.5px solid #24a0ed; } .input-label { background-color: white; position: absolute; color: #aaa; top: 0.55rem; left: 0.75rem; font-size: 0.9rem; z-index: 2; transition: .3s; pointer-events: none; } .text-input:focus + .input-label { top: -0.55rem; left: 0.5rem; transform: scale(0.75); color: #24a0ed; font-weight: 500; } /* placeholder 沒有顯示狀態下,且沒有focus的 text-input */ .text-input:not(:placeholder-shown).text-input:not(:focus) + .input-label { top: -0.55rem; left: 0.5rem; transform: scale(0.75); color: #aaa; font-weight: 500; }
其他:實現按鈕居右
第一種:設定按鈕所在的容器設為 displaye: flex
+ justify-content: flex-end
:
.sign-btn-wrapper {
margin-left: auto;
display: block;
}
第二種,設定按鈕本身,聯合使用 displaye: block
和 margin-left: auto
:
.sign-btn-wrapper .sign-btn {
margin-left: auto;
display: block;
}