jquery制作属于自己的select自定义样式

2020-05-27 18:08:16易采站长站整理

由于原生select在各个浏览器的样式不统一,特别是在IE67下直接不可以使用样式控制,当PM让你做一个样式的时候,那是相当的痛苦。最好的办法就是使用自定义样式仿select效果。这里写了一个jquery插件,实现自定义的select(阉割了不少原生select的事件,但是最主要的都还在)
需要引用的样式:


.self-select-wrapper{
position: relative;
display: inline-block;
border: 1px solid #d0d0d0;
width: 250px;
height:40px;
font-size: 14px;
}

div.self-select-wrapper{
/*解决IE67 块级元素不支持display:inline-block*/
*display:inline;
}

.self-select-wrapper .self-select-display{
display: inline-block;
cursor: pointer;
width:100%;
height:40px;
background: -moz-linear-gradient(top, #fff, #eee);
background: -o-linear-gradient(top,#fff, #eee);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#eee));
filter: progid:DXImageTransform.Microsoft.Gradient(gradientType=0,startColorStr=#ffffff,endColorStr=#eeeeee);
}

.self-select-display .self-select-text{
padding-left:10px;
display: inline-block;
line-height: 40px;
width: 210px;
}

.self-select-display .self-select-arrow-down{
height:0;
width:0;
overflow: hidden;
font-size: 0;
line-height: 0;
display: inline-block;
vertical-align: middle;
border-color:#aaa transparent transparent transparent;
border-style:solid dashed dashed dashed;
border-width:7px;
}

.self-select-wrapper .self-select-ul{
position: absolute;
max-height:200px;
_height:200px;
border: 1px solid #ccc;
background-color: #fff;
top:41px;
left:0px;
overflow-y: auto;
_overflow-y:auto !important;
padding:0px;
margin:0px;
width: 100%;
z-index:2014;
display: none;
}

.self-select-wrapper .self-select-ul li{
list-style: none;
}

.self-select-ul .self-select-option{
line-height: 28px;
cursor: pointer;
display: block;
padding-left:10px;
text-decoration: none;
color:#000;
}

.self-select-ul .self-select-option:hover,
.self-select-ul .current{
background-color: #eee;
}

js源码:


/**
* 解决自定义select自定义样式需求
* select父级元素谨慎使用z-index
*/
(function($){
var tpl = '<div class="self-select-wrapper">'+
'<span class="self-select-display">'+
'<span class="self-select-text"></span>'+
'<i class="self-select-arrow-down"></i>'+
'</span>'+
'<ul class="self-select-ul"></ul>'+
'</div>';

$.fn.selfSelect = function(changeHandler){
var name = $(this).attr('name');