JavaScript——下拉菜单实现

这篇博客展示了如何利用JavaScript动态创建一个交互式的下拉菜单。通过将标题和子菜单项存储在数组中,然后遍历这些数组来生成HTML元素。当鼠标悬停在菜单项上时,对应的子菜单会显示出来,并且可以改变选中项的样式。此外,通过设置CSS样式和事件监听器,实现了菜单项的布局和交互效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin:0px;
padding: 0px;
}
#one{

}
#one li{
width: 50px;
height: 30px;
border:1px solid black;
text-align: center;
list-style: none;
float: left;
line-height: 30px;
}
#two li{
width: 50px;
height: 30px;
border:1px solid black;
list-style: none;
line-height: 30px;
text-align: center;
/*clear: both;*/
}
#two{
position: absolute;
top: 30px;
}
.select{
background: rgb(0,200,0);
}
</style>
</head>
<body>
<ul id="one"></ul>
<ul id="two"></ul>
<script type="text/javascript">
var arr1=["标题一","标题二"];
var arr2=[["a","b","c","d"],["one","two","three","four"]];
var one=document.getElementById('one');
var two=document.getElementById('two');
for(var n=0;n<arr1.length;n++){
var li=document.createElement("li");
li.innerHTML=arr1[n];
one.appendChild(li);
}
var li=document.getElementsByTagName('li');
for(var n=0;n<li.length;n++){
li[n].value=n;
li[n].onmouseover=function(){
for(var n=0;n<li.length;n++){
li[n].className="";
}
li[this.value].className="select";


var str="";
for(var n=0;n<arr2[this.value].length;n++){
str=str+"<li>"+arr2[this.value][n]+"</li>";
}
two.innerHTML=str;
two.style.left=(this.value*52)+"px";
}
}
one.onmouseover=function(){
two.style.display="block";
}
one.onmouseout=function(){
two.style.display="none";
}
two.onmouseover=function(){
two.style.display="block";
}
two.onmouseout=function(){
two.style.display="none";
}
</script>


</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值