javascript模拟select菜单的代码示例

发布时间:2020-09-27编辑:脚本学堂
本篇文章介绍了,用Javascript实现模拟select菜单效果的代码,用到了javascript的闭包与继承,有需要的朋友,可以参考下。

1、css部分
 

<style type="text/css">
<!--
*{padding:0; margin:0;}
ul{list-style:none; margin:10px 30px; position:relative; font-family:"宋体";}
ul li{position:relative; width:202px;height:22px; }
.text{width:200px; height:20px; position:absolute; left:0; top:0;border:1px solid #ccc; line-height:20px; font-size:14px; cursor:default;}
.btn{position:absolute;width:17px; height:20px; right:1px; top:1px; display:inline-block; background:url(http://file.jb200.com/img/201008/btn_thumb_1.jpg) no-repeat;}
.btnhover{background:url(http://file.jb200.com/img/201008/btn2_thumb.jpg);}
.select{border:1px solid #666;width:199px; height:auto; position:absolute; top:21px; display:none;background:#fff;}
.select p{line-height:16px; font-size:13px; cursor:default; position:relative;}
.select .hover{background:#3399FD;}
--></style>

2、页面内容部分
 

复制代码 代码示例:
<h2>浏览器默认样式</h2>
<p>
<select style="width: 200px; margin: 10px 30px; height: 22px; border: 1px solid #ccc; font-size: 14px; z-index: 0;"><option>select1</option><option>select2</option><option>select3</option><option>select4</option></select></p>
<h2>js模拟select,样式主要参照IE8与Firefox。</h2>
<ul>
<li><input type="text" class="text" onclick="beginSelect(this);" /><span class="btn" onmousedown="beginSelect(this)"> </span></li>
<li class="select">
<p>select1</p>
<p>select2</p>
<p>select3</p>
<p>select4</p>
</li>
</ul>
<p>在不改变HTML结构的前提下,可更改其它样式。建议用IE8与FF浏览,可与默认样式进行对比。</p>

3、js代码部分
 

复制代码 代码示例:
<script type="text/javascript">
/**
 * 模拟select菜单
 * Edit www.jb200.com
*/
// <![CDATA[
function beginSelect(elem){
if(elem.className == "btn"){
elem.className = "btn btnhover"
elem.onmouseup = function(){
this.className = "btn"
}
}
var ul = elem.parentNode.parentNode;
var li = ul.getElementsByTagName("li");
var selectArea = li[li.length-1];
if(selectArea.style.display == "block"){
selectArea.style.display = "none";
}
else{
selectArea.style.display = "block";
mouseoverBg(selectArea);
}
}
function mouseoverBg(elem1){
var input = elem1.parentNode.getElementsByTagName("input")[0];
var p = elem1.getElementsByTagName("p");
var pLength = p.length;
for(var i = 0; i < pLength; i++){
p[i].onmouseover = showBg;
p[i].onmouseout = showBg;
p[i].onclick = postText;
}
function showBg(){
this.className == "hover"?this.className = " ":this.className = "hover";
}
function postText(){
var selected = this.innerHTML;
input.setAttribute("value",selected);
elem1.style.display = "none";
}
}
// ]]></script>
 

在不改变HTML结构的前提下,可更改其它样式。
建议用IE8与FF浏览,可与默认样式进行对比。