<select>
<option value="">- Placeholder</option>
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
</select>
我想將未選擇的下拉選單(默認顯示占位符值)的顏色更改為淺灰色。這樣它看起來更像是一個placeholder像輸入一樣的欄位。
特別是,一旦選擇了實際值,顯示的文本不應恢復正常。
https://jsfiddle.net/bq32uxh7/
uj5u.com熱心網友回復:
為確保無法選擇占位符值,您可以將其設定為禁用。在大多數瀏覽器中,當它未被選中時會顯示為淺灰色,因此無法選擇。
<select>
<option value="" selected disabled>- Placeholder</option>
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
</select>
如果您不希望占位符出現在選項串列中,您甚至可以使用 hidden 屬性隱藏它:
<option value="" selected disabled hidden>- Placeholder</option>
如果您想進一步設定樣式,請參閱@Rippo 的回答。
編輯:如果您想在所選選項無效(即占位符)時更改選擇輸入的外觀,您需要根據需要設定選擇輸入,然后您可以:invalid在選擇的 css 選擇器上使用偽類。
select:invalid {
background-color: gray;
}
<select required>
<option value="" selected disabled>- Placeholder</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
uj5u.com熱心網友回復:
這會讓你接近嗎?
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('form-select').addEventListener('change', function() {
if (this.value === "") {
if (!this.classList.contains('placeholder')) {
this.classList.add('placeholder');
}
if (this.classList.contains('others')) {
this.classList.remove('others');
}
} else {
if (!this.classList.contains('others')) {
this.classList.add('others');
}
if (this.classList.contains('placeholder')) {
this.classList.remove('placeholder');
}
}
});
});
#form-select {
color: #8e8e8e;
}
#form-select.placeholder, option.placeholder {
color: #8e8e8e;
}
#form-select.others, option.others {
color:#000;
}
<select id="form-select" aria-label="Default select example">
<option class="placeholder" value="" selected>- Placeholder</option>
<option class="others" value="1">One</option>
<option class="others" value="2">Two</option>
<option class="others" value="3">Three</option>
</select>
我改變了幾件事。
- 選擇選項現在有一個 id
- 每個選項都有一個類
- When you have a other item selected in dark mode things look a bit weird as the grey is forcing the background color to go into light mode. This may be possible to adjust with forcing a bg color. In light mode it works well
- You should be able to refactor the add/removing classes and create a toggle function instead
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/451821.html
