基本的select标签下拉框,采用浏览器内置样式,不能更改,极其影响用户体验。想要改变样式,一般会通过ul-li模拟下拉框。
html代码:
<ul id="select">
<li>
<div class="select-head">
<span class="select-head-cont"></span>
<span class="select-icon"><img src="./image/drop_down.png"></span>
</div>
<ul class="option">
<li class="option-item">头等舱</li>
<li class="option-item">公务舱</li>
<li class="option-item">经济舱</li>
</ul>
</li>
</ul>
css代码:
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
}
#select {
border: 1px solid #9D9D9D;
width: 250px;
height: 24px;
font-size: 12px;
cursor: pointer;
box-sizing: border-box;
padding-left: 0 10px 0 5px;
}
.select-head {
overflow: hidden;
width: 100%;
height: 24px;
box-sizing: border-box;
padding-left: 5px;
line-height: 24px;
}
.select-head .select-head-cont {
float: left;
}
.select-head .select-icon {
float: right;
margin-right: 10px;
}
.option {
margin-top: 1px;
width: 250px;
color: black;
background: #fff;
border: 1px #9D9D9D solid;
display: none;
z-index: 10;
position: absolute;
box-sizing: border-box;
top: 23px;
left: 0;
}
.option .option-item {
margin-bottom: 0;
height: 24px;
line-height: 24px;
padding-left: 5px;
}
.option-item:hover {
background: #2F4050 !important;
color: #fff !important;
}
js代码:
$(function() {
var selectHeadCont = document.getElementsByClassName('select-head-cont');
var optionItem = document.getElementsByClassName('option-item');
/*默认是第一个选项*/
selectHeadCont[0].innerHTML = optionItem[0].innerHTML;
optionItem[0].setAttribute('style', 'background: #2F4050; color:#fff');
/*点击选项后出现在下拉框*/
var len = optionItem.length;
for (var i = 0; i < len; i++) {
optionItem[i].index = i;
optionItem[i].addEventListener('click', function() {
selectHeadCont[0].innerHTML = optionItem[this.index].innerHTML;
// 初始化所有optionItem背景样式
for (var k = 0; k < len; k++) {
optionItem[k].setAttribute('style', 'background: #fff; color:#333333');
}
// 给选中的optionItem添加背景样式
optionItem[this.index].setAttribute('style', 'background: #2F4050; color:#fff');
$('.option').css('display', 'none');
}, false);
}
// 阻止冒泡事件发生
function stopPropagation(e) {
if (e.stopPropagation)
e.stopPropagation(); //停止冒泡 非ie
else
e.cancelBubble = true; //停止冒泡 ie
}
// 点击select-head时,select出现
$('.select-head').on('click', function(e) {
$('.option').css('display', 'block');
stopPropagation(e);
})
// 点击其他地方时,select会收起来
$(document).on('click', function(event) {
$('.option').css('display', 'none');
})
})
结果为: