JavaScript实现Select下拉框美化与模拟功能详解

作者:像素猫时间:2026-10-23 01:49:12浏览:429

本文详细介绍如何使用JavaScript美化原生Select下拉框。通过隐藏原始控件,利用DIV和UL模拟显示与交互,实现自定义样式。代码涵盖定位、事件处理及值同步逻辑,确保表单提交时能正确获取选中值,解决CSS无法直接美化Select的难题。

引言与功能概述

论坛中常有人询问如何利用CSS美化Select标签,但实际上,那些视觉效果出色的下拉菜单通常都是借助JavaScript实现的。笔者昨日尝试编写了一个基础版本,实现了初步功能,现整理出来与大家分享。大家可以访问 http://www.iwcn.net/demo/select 查看演示效果。



【功能需求】


1、调用方式需简便,完成后的使用示例如下:



程序代码



function loadSelect(selectobj){


//传入一个select对象就能将他的样式美化


}


2、保持原有表单结构不变,不破坏页面HTML代码:



程序代码



<form name="f" onsubmit="getResult();">


<fieldset>


<legend>用户注册</legend>


<div>


<label for="username">帐号</label>


<input type="text" id="username" name="username" />


</div>


<div>


<label for="pwd">密码</label>


<input type="password" name="pwd" id="pwd" />


</div>


<div>


<label for="province">省份</label>


<select id="province" name="province">


<option value="10">江西</option>


<option value="11">福建</option>


<option value="12">广东</option>


<option value="13">浙江</option>


</select>


</div>


</fieldset>


<input type="submit" value="提交" name="btnSub" />


</form>





核心实现思路

【实现思路】



第一步:将表单中的原生select元素隐藏。


原因很简单,原生select控件受浏览器内核限制,CSS难以对其内部样式进行精细控制,因此需要将其隐藏。



第二步:通过脚本计算select标签在页面中的绝对坐标位置。


在该坐标位置创建一个外观美观的DIV元素,作为select的替身显示。



第三步:通过脚本读取select标签内的所有选项值。


虽然select被隐藏,但其内部的options数据仍需保留,需全部提取出来供后续使用。



第四步:当用户点击select的替身(即DIV)时,在下方动态生成另一个DIV,用于展示下拉选项列表。



整体逻辑大致如此,接下来我们将分步实现具体代码。



准备工作与代码实现

【准备工作】


1、确定select的美化样式,并准备好相应的背景图片。此处准备了两张小图,分别对应下拉箭头默认状态和鼠标悬停状态。


2、编写一个普通的表单提交页面,例如以下示例。注意为select定义了基础CSS样式,在头部引入了JS文件,并在body中添加了调用函数的脚本。


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">     <head>     <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />     <meta http-equiv="Content-Language" content="zh-CN" />     <title>用javascript美化Select</title>          <style type="text/css">     select{width:200px;height:20px;} </style>     </head>     <body>         <h1>用javascript模拟select达到美化效果</h1>               <p>         http://www.iwcn.net">作者博客     </p>     </body> </html> 

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]


【编写javascript】



程序代码


<script type="text/javascript" src="select.js"></script>



新建一个js文件并保存为select.js,后续所有逻辑均在该文件中完成。



函数名:loadSelect(obj);


参数:select对象



相关函数:



程序代码



function Offset(e)


//取标签的绝对位置


{

var t = e.offsetTop;


var l = e.offsetLeft;


var w = e.offsetWidth;


var h = e.offsetHeight-2;



while(e=e.offsetParent)


    {

t+=e.offsetTop;


l+=e.offsetLeft;


    }

return {


top : t,


left : l,


width : w,


height : h


    }
}


第一步:记录select的绝对位置,以便替身元素能准确定位。



程序代码



var offset=Offset(obj);


//这里解释一下Offset是一个函数,用来获取对象的绝对位置。写在loadSelect()函数外边的。他有四个属性分别是top/left/width/height。




第二步:将原生select隐藏。



程序代码



obj.style.display="none";




第三步:创建一个虚拟DIV代替select显示。



程序代码



var iDiv = document.createElement("div");


iDiv.id="selectof" + obj.name;


iDiv.style.position = "absolute";


iDiv.style.width=offset.width + "px";


iDiv.style.height=offset.height + "px";


iDiv.style.top=offset.top + "px";


iDiv.style.left=offset.left + "px";


iDiv.style.background="url(icon_select.gif) no-repeat right 4px";


iDiv.style.border="1px solid #3366ff";


iDiv.style.fontSize="12px";


iDiv.style.lineHeight=offset.height + "px";


iDiv.style.textIndent="4px";


document.body.appendChild(iDiv);




第四步:将原始select默认选中的值显示在替身DIV中。



程序代码


iDiv.innerHTML=obj.options[obj.selectedIndex].innerHTML;



第五步:为替身添加鼠标悬停样式效果。



程序代码



iDiv.onmouseover=function(){//鼠标移到


iDiv.style.background="url(icon_select_focus.gif) no-repeat right 4px";


    }

iDiv.onmouseout=function(){//鼠标移走


iDiv.style.background="url(icon_select.gif) no-repeat right 4px";


    }


第六步:添加关键的鼠标点击事件处理。



程序代码



iDiv.onclick=function(){//鼠标点击


if (document.getElementById("selectchild" + obj.name)){


//判断是否创建过div


if (childCreate){


//判断当前的下拉是不是打开状态,如果是打开的就关闭掉。是关闭的就打开。


document.getElementById("selectchild" + obj.name).style.display="none";


childCreate=false;


}else{


document.getElementById("selectchild" + obj.name).style.display="";


childCreate=true;


            }

}else{


//初始一个div放在上一个div下边,当options的替身。


var cDiv = document.createElement("div");


cDiv.id="selectchild" + obj.name;


cDiv.style.position = "absolute";


cDiv.style.width=offset.width + "px";


cDiv.style.height=obj.options.length *20 + "px";


cDiv.style.top=(offset.top+offset.height+2) + "px";


cDiv.style.left=offset.left + "px";


cDiv.style.background="#f7f7f7";


cDiv.style.border="1px solid silver";



var uUl = document.createElement("ul");


uUl.id="uUlchild" + obj.name;


uUl.style.listStyle="none";


uUl.style.margin="0";


uUl.style.padding="0";


uUl.style.fontSize="12px";


cDiv.appendChild(uUl);


document.body.appendChild(cDiv);


childCreate=true;


for (var i=0;i<obj.options.length;i++){


//将原始的select标签中的options添加到li中


var lLi=document.createElement("li");


lLi.id=obj.options[i].value;


lLi.style.textIndent="4px";


lLi.style.height="20px";


lLi.style.lineHeight="20px";


lLi.innerHTML=obj.options[i].innerHTML;


uUl.appendChild(lLi);


            }

var liObj=document.getElementById("uUlchild" + obj.name).getElementsByTagName("li");


for (var j=0;j<obj.options.length;j++){


//为li标签添加鼠标事件


liObj[j].onmouseover=function(){


this.style.background="gray";


this.style.color="white";


                }

liObj[j].onmouseout=function(){


this.style.background="white";


this.style.color="black";


                }

liObj[j].onclick=function(){


//做两件事情,一是将用户选择的保存到原始select标签中,要不做的再好看表单递交后也获取不到select的值了。


obj.options.length=0;


obj.options[0]=new Option(this.innerHTML,this.id);


//同时我们把下拉的关闭掉。


document.getElementById("selectchild" + obj.name).style.display="none";


childCreate=false;


iDiv.innerHTML=this.innerHTML;


                }
            }
        }
    }


最后这个比较复杂一点,再解释一下,我们在做这一步之前,select的样子已经出来了,下一步就是再加一个div去模仿select被点击之后出现的下拉选项了。我们可以讲select标签的options通过javascript提取出来,把它写成这样:



程序代码



<div>


<ul>


<li>optionName</li>


<li>optionName</li>


<li>optionName</li>


</ul>


</div>





基本上就这样了。还有些缺陷,有时间大家可以一起补充!


代码如下:

/************************************ 
* js模拟Select *
* Author:Daviv *
* Date:2007-4-28 *
* Blog:http://www.iwcn.net *
* Email:jxdawei#163.com *
************************************/ 
var childCreate=false;
function Offset(e)
//取标签的绝对位置
{ 
var t = e.offsetTop;
var l = e.offsetLeft;
var w = e.offsetWidth;
var h = e.offsetHeight-2;
while(e=e.offsetParent)
    { 
t+=e.offsetTop;
l+=e.offsetLeft;
    } 
return {
top : t,
left : l,
width : w,
height : h
    } 
} 
function loadSelect(obj){
//第一步:取得Select所在的位置
var offset=Offset(obj);
//第二步:将真的select隐藏
obj.style.display="none";
//第三步:虚拟一个div出来代替select
var iDiv = document.createElement("div");
iDiv.id="selectof" + obj.name;
iDiv.style.position = "absolute";
iDiv.style.width=offset.width + "px";
iDiv.style.height=offset.height + "px";
iDiv.style.top=offset.top + "px";
iDiv.style.left=offset.left + "px";
iDiv.style.background="url(icon_select.gif) no-repeat right 4px";
iDiv.style.border="1px solid #3366ff";
iDiv.style.fontSize="12px";
iDiv.style.lineHeight=offset.height + "px";
iDiv.style.textIndent="4px";
document.body.appendChild(iDiv);
//第四步:将select中默认的选项显示出来
var tValue=obj.options[obj.selectedIndex].innerHTML;
iDiv.innerHTML=tValue;
//第五步:模拟鼠标点击
iDiv.onmouseover=function(){//鼠标移到
iDiv.style.background="url(icon_select_focus.gif) no-repeat right 4px";
    } 
iDiv.onmouseout=function(){//鼠标移走
iDiv.style.background="url(icon_select.gif) no-repeat right 4px";
    } 
iDiv.onclick=function(){//鼠标点击
if (document.getElementById("selectchild" + obj.name)){
//判断是否创建过div
if (childCreate){
//判断当前的下拉是不是打开状态,如果是打开的就关闭掉。是关闭的就打开。
document.getElementById("selectchild" + obj.name).style.display="none";
childCreate=false;
}else{
document.getElementById("selectchild" + obj.name).style.display="";
childCreate=true;
            } 
}else{
//初始一个div放在上一个div下边,当options的替身。
var cDiv = document.createElement("div");
cDiv.id="selectchild" + obj.name;
cDiv.style.position = "absolute";
cDiv.style.width=offset.width + "px";
cDiv.style.height=obj.options.length *20 + "px";
cDiv.style.top=(offset.top+offset.height+2) + "px";
cDiv.style.left=offset.left + "px";
cDiv.style.background="#f7f7f7";
cDiv.style.border="1px solid silver";
var uUl = document.createElement("ul");
uUl.id="uUlchild" + obj.name;
uUl.style.listStyle="none";
uUl.style.margin="0";
uUl.style.padding="0";
uUl.style.fontSize="12px";
cDiv.appendChild(uUl);
document.body.appendChild(cDiv);
childCreate=true;
for (var i=0;i<obj.options.length;i++){
//将原始的select标签中的options添加到li中
var lLi=document.createElement("li");
lLi.id=obj.options[i].value;
lLi.style.textIndent="4px";
lLi.style.height="20px";
lLi.style.lineHeight="20px";
lLi.innerHTML=obj.options[i].innerHTML;
uUl.appendChild(lLi);
            } 
var liObj=document.getElementById("uUlchild" + obj.name).getElementsByTagName("li");
for (var j=0;j<obj.options.length;j++){
//为li标签添加鼠标事件
liObj[j].onmouseover=function(){
this.style.background="gray";
this.style.color="white";
                } 
liObj[j].onmouseout=function(){
this.style.background="white";
this.style.color="black";
                } 
liObj[j].onclick=function(){
//做两件事情,一是将用户选择的保存到原始select标签中,要不做的再好看表单递交后也获取不到select的值了。
obj.options.length=0;
obj.options[0]=new Option(this.innerHTML,this.id);
//同时我们把下拉的关闭掉。
document.getElementById("selectchild" + obj.name).style.display="none";
childCreate=false;
iDiv.innerHTML=this.innerHTML;
                } 
            } 
        } 
    } 
} 
作者最新文章