做一个下拉菜单,当点击表单元素时显示下拉菜单,鼠标放到菜单元素上时改变元素背景色,将菜单中选中的值传到表单中,当点击表单及下拉菜单时外的其他地方时,下拉菜单消失。
<title>下拉菜单</title> <style type="text/css"> * { margin:0px; padding:0px; } #pingmu { width:100%; height:100%; position:fixed; background-color:#FF9; } #minzu { width:200px; height:300px; border:1px solid #000; text-align:center; background-color:#FFF; } #minzu div { width:200px; height:50px; font-size:20px; line-height:50px; vertical-align:middle; text-align:center; } #menu { width:198px; height:50px; font-size:20px; line-height:50px; vertical-align:middle; text-align:center; } </style> </head> <body> <div id="pingmu" onclick="guan()"> <input type="text" id="menu" value="民族" onclick="xiala()"/> <div id="minzu" style="display:none"> <div id="han" onmouseover="caidan(this)" onmouseout="out(this)" onclick="quzhi(this)">汉族</div> <div id="hui" onmouseover="caidan(this)" onmouseout="out(this)" onclick="quzhi(this)">回族</div> <div id="man" onmouseover="caidan(this)" onmouseout="out(this)" onclick="quzhi(this)">满族</div> <div id="chao" onmouseover="caidan(this)" onmouseout="out(this)" onclick="quzhi(this)">朝鲜族</div> <div id="miao" onmouseover="caidan(this)" onmouseout="out(this)" onclick="quzhi(this)">苗族</div> <div id="zhang" onmouseover="caidan(this)" onmouseout="out(this)" onclick="quzhi(this)">藏族</div> </div> </div> </body> <script type="text/javascript"> function caidan(a) { a.style.backgroundColor="red"; //鼠标放上变为红色 } function out(b) { b.style.backgroundColor="white"; //鼠标移开变回白色 } function quzhi(c) { var s= c.innerText; var y=document.getElementById("menu"); //将选中的值传给表单 y.value=s; } function xiala() { document.getElementById("minzu").style.display="block"; //点击表单元素显示下拉菜单 stopEventBubble(event); } function guan() { document.getElementById("minzu").style.display="none"; //点击菜单外的屏幕部分下拉菜单消失 } function stopEventBubble(event) //阻止事件冒泡函数(阻止点击表单元素时下拉菜单消失) { var e=event || window.event; if (e && e.stopPropagation) { e.stopPropagation(); } else { e.cancelBubble=true; } }
注意:阻止事件冒泡函数(可复制直接使用)
function stopEventBubble(event) //阻止事件冒泡函数
{
var e=event || window.event;
if (e && e.stopPropagation)
{
e.stopPropagation();
}
else
{
e.cancelBubble=true;
}
}