使用原生js和css实现下拉框

时间:2022-11-21 19:43:37


因为原始select的option默认样式无法被改变,自己试着写了一个下拉框,应该还有更好的办法,以后再总结,代码如下:


html
< ul class= "select">
< li class= "drop-down" onclick= "selectShow()">
< span id= "reasontxt" class= "bgimg-down">请选择退款原因</ span>
< ul class= "drop-down-content">
< li class= "fs14 c_999">不喜欢/不想要</ li>
< li class= "fs14 c_999">空包裹</ li>
< li class= "fs14 c_999">未按照约定时间发货</ li>
< li class= "fs14 c_999">快递物流一直未送达</ li>
< li class= "fs14 c_999">货物破损已拒签</ li>
</ ul>
</ li>
</ ul>


css

.reasonBox ul li span{
display: block;
text-decoration: none;
height: 30 px;
width: 246 px;
line-height: 30 px;
border: 1 px solid #DBDBDB;
border-radius: 4 px;
padding-left: 10 px;
background-color: #fff;
color: #999;
font-size: 14 px;
}
.reasonBox .drop-down{
height: 30 px;
width: 256 px;
cursor: pointer;
}
.reasonBox .drop-down-content{
position: absolute;
display: none;
overflow: hidden;
width: 256 px;
background-color: #fff;
box-shadow: 0 1 px 6 px 0 rgba (0,0,0,0.15);
border: 1 px solid #ccc;
border-radius: 4 px;
margin-top: 2 px;
}
.reasonBox .drop-down-content li{
height: 30 px;
line-height: 30 px;
padding-left: 10 px;
}
.reasonBox .drop-down-content li :hover{
background-color: #00D2C3;
color: #fff;
}
.reasonBox .drop-down .active{
display: block;
}
.reasonBox .bgimg-down{
background: url ( ../images/aftersale/i_down.png ) no-repeat 234 px 8 px;
}
.reasonBox .bgimg-up{
background: url ( ../images/aftersale/i_up.png ) no-repeat 234 px 8 px;
}


js

< script type= "text/javascript">
//下拉框
var selectFlag = false;
function selectShow(){
var contentDom =document. getElementsByClassName( "drop-down-content")[ 0];
var imgDOM =document. getElementById( "reasontxt");
selectFlag =!selectFlag;
//展开
if(selectFlag){
contentDom.className =contentDom.className + " " + "active";
imgDOM.className = "bgimg-up";
} else{
contentDom.className = "drop-down-content";
imgDOM.className = "bgimg-down";
}
}
//监听选择退款原因点击事件
function selector(){
var ul =document. querySelectorAll( ".drop-down ul")[ 0]
ul. addEventListener( 'click', function( e){
var el =e.target
while(el.tagName !== 'LI'){
if(el ==ul){
el = null;
break;
}
el =el.parentNode
}
if (el) {
document. getElementById( "reasontxt").innerHTML =el.innerHTML
}
}, false)
}
window. onload =function(){
selector()
}
</ script>



效果图:

使用原生js和css实现下拉框