面向对象组件——下拉菜单
效果:平时在网页上经常会看到导航栏在鼠标经过时,字体颜色和背景会改变,然后会显示下拉菜单。
原理:js实现在鼠标经过时,改变字体的颜色和背景,然后下拉菜单显示。一般情况下,下拉菜单处于隐藏的状态。
代码实现:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { padding: 0; margin: 0; list-style: none; } a{ text-decoration: none; } .dropdown { width: 300px; height: 30px; margin: 100px auto; line-height: 30px; text-align: center; } .dropdown ul li { width: 100px; height: 30px; background:#6FE0CB; float: left; cursor: pointer; position: relative; } .dropdown ul ul { display: none; position: absolute; top: 30px; left: 0; text-decoration: none; } .dropdown ul li a:hover,.dropdown ul ul a:hover{ background: #48AE15; color: #fff; } </style> </head> <body> <div id="dropdown" class="dropdown"> <!-- ul>li*3>a+ul>li*3>a --> <ul> <li> <a href="">首页</a> <ul> <li><a href="">水果</a></li> <li><a href="">蔬菜</a></li> <li><a href="">主食</a></li> </ul> </li> <li> <a href="">水果</a> <ul> <li><a href="">草莓</a></li> <li><a href="">芒果</a></li> <li><a href="">葡萄</a></li> </ul> </li> <li> <a href="">蔬菜</a> <ul> <li><a href="">青菜</a></li> <li><a href="">白菜</a></li> <li><a href="">豆角</a></li> </ul> </li> </ul> </div> <script type="text/javascript" src="down.js" charset="utf-8"></script> <script> var oDown = document.getElementById('dropdown'); var drop = new Drop(oDown); drop.init(); </script> </body> </html>
js代码:
1 //构造函数:定义构造函数实例的私有属性 2 function Drop(ele){ 3 this.ele=ele; 4 this.list=this.ele.children[0].children; 5 } 6 7 //构造函数的原型对象:定义构造函数实例共享的属性和方法 8 Drop.prototype={ 9 showMenu:function(obj){ 10 obj.style.display='block'; 11 }, 12 13 hideMenu:function(obj){ 14 obj.style.display='none'; 15 }, 16 17 init:function(){ 18 var _this=this; 19 for(var i=0;i<this.list.length;i++){ 20 this.list[i].onmouseover=function(){ 21 _this.showMenu(this.children[1]); 22 } 23 this.list[i].onmouseout=function(){ 24 _this.hideMenu(this.children[1]); 25 } 26 } 27 } 28 }

浙公网安备 33010602011771号