代码改变世界

javaScript模拟select下拉菜单,满足自定义select样式的需求+jquery实现

2012-03-31 17:46  VVG  阅读(2968)  评论(1编辑  收藏  举报

SELECT列表选择不支持样式设置,抽空用JS模拟了一个SELECT的样式,如下:

下拉菜单样式模拟,模拟下拉菜单

下拉菜单样式模拟,模拟下拉菜单

 
 

 

 

代码如下:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>下拉菜单样式模拟,模拟下拉菜单</title>
<style type="text/css">
.boxa{ margin: 10px;}
#warper,#warper1{ margin:20px; position:relative; width:100px; float: left;}
#warper1{ width:202px;}
#warper ul,#warper1 ul{list-style:none; margin: 0; padding:0;}
#warper ul li,#warper1 ul li{line-height:20px; cursor:pointer; margin:1px 0; font-size:12px; text-indent:5px;}
.inputbox{width:128px; height:23px; line-height:23px; background: #ccc url(http://img.allinbuy.cn/WebResources/WSTL/Images/shopping/point/slt.gif) no-repeat; border:none; font-size:12px; text-indent:5px;}
.inputbox1{width:202px; height:23px; line-height:23px; background: #ccc ; border:1px solid #333; font-size:12px; text-indent:5px;}
.listcss{ display:none;position:absolute;width:126px;left:0;top:22px;border:1px solid #ccc; background:#fff; }
.listcss1{ display:none;position:absolute;width:202px;left:0;top:25px;border:1px solid #ccc; background:#fff; }
.hover{ background:blue; color:#fff;}
.hover1{ background:red; color:#fff;}

</style>
</head>
<body>
<form action="" method="get" name="fr">
<div class="boxa">
<!-- 设置SELECT隐藏,基本布局是一个DIV下面包裹SELECT与DIV显示框,用UL无序列表模拟SELECT的下拉菜单
需要传入DIV包裹层的id,select的ID,内层DIV的ID,UL要应用的样式,li的鼠标放上去样式-->
<div id="warper">
<select name="" id="select" style="display:none;">
<option value="北京" >北京</option>
<option value="上海">上海</option>
<option value="重庆" selected>重庆</option>
<option value="成都">成都</option>
<option value="杭州">杭州</option>
<option value="南京">南京</option>
</select>
<div class="inputbox" id = "input"></div>
</div>
<input type="submit" onclick="get('select','input'); return false" value = "测试" style="float:left; margin:20px;">
</div>
<div class="boxa">
<div id="warper1">
<select name="" id="select1" style="display:none;">
<option value="北京" >北京</option>
<option value="上海">上海</option>
<option value="重庆" selected>重庆</option>
<option value="成都">成都</option>
<option value="杭州">杭州</option>
<option value="南京">南京</option>
<option value="成都">成都</option>
<option value="杭州">杭州</option>
<option value="南京">南京</option>
<option value="成都">成都</option>
<option value="杭州">杭州</option>
<option value="南京">南京</option>
<option value="成都">成都</option>
<option value="杭州">杭州</option>
<option value="南京">南京</option>
<option value="成都">成都</option>
<option value="杭州">杭州</option>
<option value="南京">南京</option>
</select>
<div class="inputbox1" id = "input1"></div>
</div>
<input type="submit" onclick="get('select1','input1'); return false" value = "测试" style="float:left; margin:20px;">
</div>
</form>
<script type="text/javascript">
// 此处是为了测试修改数据后用的,可以去掉
function get(select,input){
var input1 = document.getElementById(select);
var input2 = document.getElementById(input);
alert("隐藏的SELECT现在的值:"+input1.value + "\ndiv框现在的值:" + input2.innerHTML);
}
</script>
<script type="text/javascript">
// 新建命名空间,可以修改成自己的
var VVG = {};
VVG.DOM = {};
// bindEvent方法,绑定事件
VVG.DOM.bindEvent = function(element,type,func){
if(element.addEventListener){
element.addEventListener(type,func,false); //false 表示冒泡
}else if(element.attachEvent){
element.attachEvent("on"+type,func)
}else{
element["on"+ type] = func;
}
};
// unbindEvent方法,取消绑定
VVG.DOM.unbindEvent = function(element,type,func){
if(element.removeEventListener){
element.removeEventListener(type,func,false);
}else if(element.detachEvent){
element.detachEvent("on"+type,func);
}else{
element["on"+type] = null;
}
};
//停止冒泡
VVG.DOM.stopPropagation = function(event){
if (event.stopPropagation) {
event.stopPropagation();
}else {
event.cancelBubble = true;
}
};
// 取消默认事件
VVG.DOM.preventDefault = function(event){
if (event.preventDefault) {
event.preventDefault();
}else {
event.returnValue = false;
}
};
// 创建一个SELECT对象的构造函数
VVG.Selector = function(o){
this.selectId = o.selectId; // 隐藏的SELECT的ID
this.divId = o.divId; // 模拟显示SELECT值DIV的 id
this.warperId = o.warperId; //包裹层的ID
this.css = o.css;//下拉菜单的样式,即UL的CLASS样式
this.liHover = o.licss; // 下拉菜单项鼠标放上去时的CSS样式
}
// 设置构造函数原型
VVG.Selector.prototype = {
checkArguments : function(){
if(this.selectId&&this.divId&&this.warperId&&this.css){
return true;
}else{
alert("传入的ID参数为空或者格式不正确!");
return false;
}
},
createUl : function(){
if(this.checkArguments()){
var sId = document.getElementById(this.selectId);
var iId = document.getElementById(this.divId);
var wId = document.getElementById(this.warperId);
var options = sId.getElementsByTagName("option"); //取得列表项
//console.log(sId.value);
iId.innerHTML = sId.value;//把SELECT的值赋给INPUT
var ul = document.createElement("ul"); //创建UL
var that = this;
for(var i = 0, n = options.length; i<n;i++){ //按照OPTIONS的长度生成标签li
var li = document.createElement("li");
li.innerHTML = options[i].value;//同步值
// 绑定事件
VVG.DOM.bindEvent(li,"mouseover",function(event){
//鼠标划过的时候设置CSS
var target = event.target || event.srcElement;
target.className = that.liHover;
});
VVG.DOM.bindEvent(li,"mouseout",function(event){
// 鼠标out的时候移除CSS
var target = event.target || event.srcElement;
target.className = "";
});
VVG.DOM.bindEvent(li,"click",function(event){
var target = event.target || event.srcElement;
// 鼠标点击的时候相关赋值
iId.innerHTML = target.innerHTML;
sId.value = iId.innerHTML;
ul.style.display = "none";
var event = event || window.event;
VVG.DOM.stopPropagation(event);
});
ul.appendChild(li);

}
wId.appendChild(ul);
ul.className = this.css;
VVG.DOM.bindEvent(iId,"click", function(event){
ul.style.display = "block";
var event = event || window.event;
VVG.DOM.stopPropagation(event);
})
VVG.DOM.bindEvent(window,"click", function(event){
// alert("1");
ul.style.display = "none";
})

}
}
}
var selector1 = new VVG.Selector({
selectId:"select",
divId:"input",
warperId:"warper",
css:"listcss",
licss:"hover"
});
selector1.createUl();
var selector2 = new VVG.Selector({
selectId:"select1",
divId:"input1",
warperId:"warper1",
css:"listcss1",
licss:"hover1"
});
selector2.createUl();
</script>
</body>
</html>

 

 

使用方法:

var selector1 = new VVG.Selector({ //新建实列
selectId:"select", //selectID
divId:"input", //内层DIV的ID
warperId:"warper",//包裹层DIV的id
css:"listcss",//ul下拉列表中UL的css
licss:"hover"//li的HOVER样式
});
selector1.createUl();

然后自定义相关select模拟层的样式


Jquery 实现方法:

/*------------------------------------------------- +
 自定义SELECT表单样式
 使用方法:WellForm(id) //id 为表单元素form id
 +------------------------------------------------- */
function WellForm(id) {
    var $mySelects = $('#' + id).find('select');
    var n = $mySelects.length;
    var z = n;
    for (var i = 0; i < n; i++) {
        var $div = $("<div class='wellSelect'></div>");
        var $ul = $("<ul></ul>");
        var $em = $("<em></em>");
        $div.css('zIndex',z--);
        $div.click(
            function(){
                $('ul',this).show();
            }
        ).mouseleave(
            function(){
                $('ul',this).hide();
            }
        );
        $div.append($em);
        $div.append($ul);
        var $myOptions = $('option', $mySelects[i]);
        var k = $myOptions.length;
        for (var j = 0; j < k; j++) {
            var $myValue = $($myOptions[j]).val() ? $($myOptions[j]).val() : $($myOptions[j]).text();
            var $li = $("<li>" + $myValue + "</li>");
            $li.hover(function(){
                $(this).addClass('hover');
            },function(){
                $(this).removeClass('hover');
            });
            $li.click(function(){
                $(this).parent().prev().html($(this).text());
                var index = $(this).parent().find('li').index(this);
                $(this).parent().parent().next().get(0).selectedIndex = index;
                $(this).parent().parent().next().trigger("change");                                            
                $(this).parent().hide();            
                return false;
            });
            if ($myOptions[j].selected == true) {
                $em.html($myValue);
            }
            $ul.append($li);
            $ul.hide();
        }
        $($mySelects[i]).parent().find('label').after($div);
        $($mySelects[i]).hide();
    }
}
$(function () {
    WellForm('wellForm');
});

所需CSS:

/** wellSelect **/
.wellSelect{ position:relative; left:4px; background-position:right -325px; width:200px;height:24px; line-height:24px;  border:1px solid #ccc; display:inline-block; _display:inline; zoom:1;}
.wellSelect ul{ position:absolute;left:-1px; top:24px; background:#fff; width:200px; border:1px solid #ccc;}
.wellSelect ul li{ padding-left:5px; background:#fff; width:195px;}
.wellSelect ul li.hover{ background:#ccc;}

HTML结构:

<form id="wellForm">
        <div class="row">
            <label class="labeltext1">常付账单:</label>
            <select name="" class="select" onchange="alert('1111');">
                <option value="123354887">123354887</option>
                <option value="987552331">987552331</option>
                <option value="875121235">875121235</option>
                <option value="745215896">745215896</option>
            </select>
            <em class="addone"><a href="#">+新建一个缴费项目</a></em>
        </div>
        <div class="row">
            <label class="labeltext1">常付账单:</label>
            <select name="" class="select">
                <option value="123354887">123354887</option>
                <option value="987552331">987552331</option>
                <option value="875121235">875121235</option>
                <option value="745215896">745215896</option>
            </select>
        </div>
</form>

运行wellform函数后HTML代码:

<div class="row">
            <label class="labeltext1">常付账单:</label>
<
div class="wellSelect" style="z-index: 4; ">
<
em>123354887</em>
<
ul style="display: none; ">
<
li>123354887</li>
<
li>987552331</li>
<
li>875121235</li>
<
li>745215896</li>
</
ul>
</
div> <select name="" class="select" onchange="alert('1111');" style="display: none; "> <option value="123354887">123354887</option> <option value="987552331">987552331</option> <option value="875121235">875121235</option> <option value="745215896">745215896</option> </select> <em class="addone"><a href="#">+新建一个缴费项目</a></em> </div>