最近做項目,要求修改select下拉框的默認三角樣式,因為它在不同瀏覽器的樣式不同且有點丑,找找網上也沒什么詳細修改方法,我就總結一下自己的吧。
目標是做成下圖效果:
圖一:將默認小三角換成紅圈的三角圖片
圖二:點擊三角圖片,同樣實現下拉框選擇
1.HTML
1 <div class="withArrow"> 2 <label for="">類型</label> 4 <span class="testArrow "> 5 <span class="defaultVaule">所有分支機構</span> 6 <select name="depts"> 7 <option value="0">所有分支機構</option> 8 <option value="1">特定部門</option> 9 </select> 10 </span> 11 </div>
結合html和css,大概是下圖的結構:
最外層div(withArrow)包裹一個label和select,在select外包裹一層span(testArrow),設置testArrow的背景為你想要的三角圖片,在select里定位一個span (defaultValue) 放點擊選擇的option的值。ok~
二、css ( 直接拷貝自項目,有些樣式很多余)
1.withArrow
.withArrow{ font-size: 0; /*清除label和input之間的間距*/ position: relative; }
2.testArrow
.withArrow .testArrow{ position: relative; display: inline-block; vertical-align: middle; width: 230px; height: 26px; right:0; top:0; box-sizing: border-box; background: url(../images/u1798.png) no-repeat 98% center; /*背景三角圖片*/ border: 1px solid rgba(225, 225, 225); }
3. label
1 .withArrow label { 2 display: inline-block; 3 width: 124px; 4 vertical-align: middle; 5 font-size: 14px; 6 color: #797979; 7 }
4.select
.withArrow .testArrow select{ appearance:none; -webkit-appearance: none; /*去除chrome瀏覽器的默認下拉圖片*/ -moz-appearance: none; /*去除Firefox瀏覽器的默認下拉圖片*/ }
.withArrow .testArrow>select{ width: 100%; height: 26px; position: absolute; top: 0; left: 0; opacity: 0; /*把select透明化*/ }
5.defaultValue
.withArrow .defaultVaule{ position: absolute; left:0; top:0; font-size: 14px; padding-left: 5px; height:26px; line-height: 26px; }
三、js
結合html和css,此時點擊背景三角圖片時,select下拉列表已經可以出現!革命完成一大半!
但是點擊選擇option后,輸入框還是空白?
因為select設置了透明度為0,有值選中但是看不到,所以需要把選中值賦給定位在select里的span標簽存放)。
所以利用事件委托原理,給testArrow綁定click事件。
(下面的寫法需引入 jquery )
$('.testArrow').click(function(e){
if(e.target.tagName.toLowerCase()=='select'){
var selectValue= $(e.target).find('option:selected').text();
$(e.target).prev().text(selectValue);
}
})
寫這個真累~ O了 ~ 下班啦哈哈