我正在創建自定義HTML5 <select>
菜單。按照設計,我試圖根據所選元素更改select
元素的顏色。基本上我需要打開菜單時#555555
的顏色,當選擇的元素不是第一個元素時,並且#c7cacb用於選擇第一個元素的關閉菜單。使用jQuery控制<select>的打開/關閉
問題出現在用戶打開菜單,選擇第一個選項,然後再次打開菜單時:所有元素都是#c7cacb。如果使用jQuery(我沒有找到方法)或其他方式(在此處堆疊)獲得菜單打開|關閉狀態,將很容易控制顏色。我怎樣才能做到這一點?
這是我的代碼:
$(document).ready(function(){
// wrap all selectors to add ::after in css
$('select:not([disabled])').wrap('<label class="dropdown">');
$('select[disabled]').wrap('<label class="dropdownDisabled">');
// controlling color of elements
$('select').click(function(){
var thisDropdown= $(this);
if($(thisDropdown).prop('selectedIndex') == 0){
thisDropdown.css('color', '#555555');
thisDropdown.click(function(){
if($(thisDropdown).prop('selectedIndex') == 0) {
thisDropdown.css('color', '#c7cacb');
}
});
}
});
})
/*dropdown styling*/
select {
width: 230px;
height: 46px;
background: #f1f5f8;
color:#c7cacb;
font-size: 16pt;
padding: 3px;
border: 2px solid #d7d6d5;
border-radius: 8px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
select::-ms-expand {/*removing dropdown arrow for IE*/
display: none;
}
.dropdownlabel {display: block; font-size: 16pt; margin-bottom: 10px; color: #d7d6d5}
label.dropdown::after {/*adding custom arrow*/
content: "\e90e";
font-family: 'icomoon';
font-size: 8pt;
color: #555555;
\t display:inline-block;
\t box-sizing:border-box;
margin-left: -32px;
pointer-events :none; /* let the click pass trough */
}
select[disabled] {
\t color: #c7cacb;
\t border: 2px solid #e4e5e6;
}
label.dropdownDisabled::after {
content: "\e90e";
font-family: 'icomoon';
font-size: 8pt;
color: #d3d5d7;
\t display:inline-block;
\t box-sizing:border-box;
margin-left: -32px;
pointer-events :none; /* let the click pass trough */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="selected" class="dropdownlabel">Dropdown label</label>
<select name="selected">
<option value="s">None Selected</option>
<option value="s2">Selected</option>
<option value="s3">Another value</option>
</select>
你有沒有考慮過使用Select2插件? – Barmar
就像Barmar說的那樣,使用Select2插件。我使用它並覆蓋類來獲得我想要的顏色效果 – Bindrid
@Barmar未嘗試Select2呢。希望找到沒有外部插件的解決方案。 – Yevhen