試一試
label {
display: block;
margin-top: 1em;
}
input:valid {
background-color: ivory;
border: none;
outline: 2px solid deepskyblue;
border-radius: 5px;
accent-color: gold;
}
<form>
<label for="email">Email Address:</label>
<input id="email" name="email" type="email" value="na@me@example.com" />
<label for="secret">Secret Code: (lower case letters)</label>
<input id="secret" name="secret" type="text" value="test" pattern="[a-z]+" />
<label for="age">Your age: (18+)</label>
<input id="age" name="age" type="number" value="5" min="18" />
<label
><input name="tos" type="checkbox" required checked /> - Do you agree to
ToS?</label
>
</form>
這個偽類對於為使用者突出顯示正確欄位很有用。
語法
css
:valid {
/* ... */
}
無障礙
綠色通常用於表示有效輸入。患有某些型別色盲的人將無法確定輸入的狀態,除非它伴有不依賴顏色傳達意義的額外指示。通常使用描述性文字和/或圖示。
示例
指示有效和無效的表單欄位
在這個例子中,我們使用這樣的結構,其中包含額外的 <span> 來生成內容;我們將使用它們來提供有效/無效資料的指示器。
html
<div>
<label for="fname">First name *: </label>
<input id="fname" name="fname" type="text" required />
<span></span>
</div>
為了提供這些指示器,我們使用以下 CSS
css
input + span {
position: relative;
}
input + span::before {
position: absolute;
right: -20px;
top: 5px;
}
input:invalid {
border: 2px solid red;
}
input:invalid + span::before {
content: "✖";
color: red;
}
input:valid + span::before {
content: "✓";
color: green;
}
我們將 <span> 設定為 position: relative,以便我們可以相對地定位生成的內容。然後我們根據表單資料是有效還是無效來絕對定位不同的生成內容——分別是綠色對勾或紅色叉號。為了給無效資料增加一點緊迫感,我們還在無效時給輸入框設定了粗紅色邊框。
注意:我們使用 ::before 來新增這些標籤,因為我們已經使用 ::after 來新增“必填”標籤。
您可以在下面嘗試
請注意,必填文字輸入在為空時無效,但在填充內容時有效。另一方面,電子郵件輸入在為空時有效,因為它不是必填項,但當它包含的不是正確電子郵件地址時則無效。
規範
| 規範 |
|---|
| HTML # 選擇器-有效 |
| 選擇器 Level 4 # 有效-偽類 |
瀏覽器相容性
載入中…