js模拟select下拉选择框,样式主要参照IE8与Firefox,在不改变HTML结构的前提下,可更改其它样式。建议用IE8与FF浏览,可与默认样式进行对比。最近在研究javascript的闭包与继承,写这个小东西找找感觉,不保证应用中能正常使用,仅用于自娱自乐。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Js模拟select选择框</title>
<style type="text/css">
*{padding:0; margin:0;}
ul{list-style:none; margin:10px 30px; position:relative;}
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(/jscss/demoimg/201008/btn_thumb_1.jpg) no-repeat;}
.btnhover{background:url(/jscss/demoimg/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>
</head>
<body>
<h2>传统样式</h2>
<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>
<h2>Js模拟的select</h2>
<ul>
<li><input type="text" class="text" /><span class="btn" οnmοusedοwn="beginSelect(this)"></span></li>
<li class="select">
<p>select1</p>
<p>select2</p>
<p>select3</p>
<p>select4</p>
</li>
</ul>
<script type="text/javascript">
function beginSelect(elem){
if(elem.className == "btn"){
elem.className = "btn btnhover"
elem. = 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]. = showBg;
p[i]. = 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>
</body>
</html>
转载于:https://blog.51cto.com/chunzhisu/1529544