效果
一级菜单列表:

当鼠标放上去后,显示二级菜单,移开后二级菜单消失:

代码
HTML代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| <div id="menu"> <ul> <li><a href="">11111</a> <ul> <li>1-1</li> <li>1-2</li> <li>1-3</li> <li>1-4</li> <li>1-5</li> <li>1-6</li> <li>1-7</li> <li>1-8</li> </ul> </li> <li><a href="">22222</a> <ul> <li>2-1</li> <li>2-2</li> <li>2-3</li> <li>2-4</li> <li>2-5</li> </ul> </li> <li><a href="">33333</a> <ul> <li>3-1</li> <li>3-2</li> <li>3-3</li> <li>3-4</li> <li>3-5</li> </ul> </li> <li><a href="">44444</a></li> <li><a href="">55555</a></li> </ul> </div>
|
less代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| body{ font-family: sans-serif; font-size: 12px; line-height: 1.5; } #menu ul{ margin:0; padding:0; list-style:none; border: 1px solid #ccc; width: 100px;
li{ text-align: center; position:relative; background-color: #eeeeee; height: 26px; line-height: 26px; border-bottom: 1px solid #cccccc;
a{ color:#000; text-decoration: none;
&:hover{ color: #ff0000; } }
ul{ position: absolute; left: 100px; top: 0px; display: none; }
&.current ul{ display: block; } } }
|
JavaScript代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| startList = function () { var navRoot = document.getElementById('menu'); var ali = navRoot.getElementsByTagName('li'); for(var i=0;i<ali.length;i++){ var node = ali[i]; node.onmouseover = function () { this.className += 'current'; } node.onmouseout = function () { this.className = this.className.replace('current',''); } } }
window.onload = startList();
|
要点
- 首先让二级菜单隐藏:
ul {display: none;},然后css中写一个有’current’类名的li(第一层),样式为ul li.current {display: block;},这个属性将通过js添加,即鼠标在上面的时候有这个属性,鼠标移出之后,没有这个属性(当然设置了之后,还得写个清除的句子)
- 如果按html中的摆放的话,会出现,一级菜单与二级菜单错位的情况,这需要通过设置css.让一级菜单的li为相对定位,二级菜单的ul绝对定位到一级菜单li的右边。