ul模拟select,位置,数据,是否可输入及输入提示效果都可作为参数直接传入

时间:2024-12-13 21:03:38

转发请注明出处,虽然转发几率不大。。。

HTML

<span class="theContainer"></span>

CSS

    body {padding:10px;}
* {margin:; padding:; font-size:12px;}
ul,li
{
list-style-type:none;
}
.theMockSelect{
width: 160px;
display: inline-block;
line-height: 20px;
position: relative;
}
.mockSelectBox{
display: block;
width: 180px;
overflow: hidden;
}
.liContainer{
width: 160px;
}
.liContainer li{
line-height:25px;
padding-left:5px;
display: block;
min-width: 170px;
}
.liContainer li:hover{
display:block;
background: #ccc;
}
.clickIcon{
position: absolute;
right: -10px;
top: 12px;
width:;
height:;
border-top: 8px solid #aaa;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 5px solid transparent;
}
.theInput{
display: block;
width: 90%;
height: 28px;
padding: 2px 8px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}

JS

 $(document).ready(function () {
var theMockSelect = {
className:'theMockSelect', //一个ul的id,放模拟框
dataArray:['first','second','third','forth'],//数组数据 init:function(theContainer,data,flag){
this.className = theContainer?theContainer:this.className;
this.dataArray = data?data:this.dataArray; var allTheLi='',theDataArray = this.dataArray;
$('.'+this.className).append('<ul class="theMockSelect"><li class="mockSelectBox"><input class="theInput" type="text" readonly="readonly"/><div class="clickIcon"></div><ul class="liContainer"></ul></li></ul>'); for(var i=0,l=theDataArray.length;i<l;i++){
allTheLi += '<li>'+theDataArray[i]+'</li>';
} $('.liContainer').append(allTheLi);
//根据参数看是否想输入
$('.theInput').prop('readonly',flag);
this.allTheEvent();
},
allTheEvent:function(){
$('.liContainer').hide();
//点击下拉
$('.clickIcon').on('click',function () { //鼠标移动函数
var theUl = $(this).parent().find('.liContainer');
if(theUl.is(':hidden')) {
theUl.children().show();
theUl.slideDown(); //找到ul.son_ul显示
$(this).parent().find('li').hover(function () {
$(this).addClass('hover');
}, function () {
$(this).removeClass('hover')
});
}else {
theUl.slideUp();
}
});
//点击子元素
$('.liContainer li').on('click',function () {
$(this).parent().parent().find('input').val($(this).html());
$(this).parent().slideUp();
});
//输入事件
$('.theInput').on('keyup',function(){
var youInput = $(this).val();
$('.liContainer li').each(function(index,item){
if($(item).text().indexOf(youInput)>=0&&youInput!==''){
$(item).show();
$('.liContainer').slideDown();
}else {
$(item).hide();
}
});
});
}
}; theMockSelect.init('theContainer',['666','555','333','111'],false);
});