常见的后台管理模板都有一个伸缩菜单,我们可以通过CSS轻松实现,但是如果我们动态的添加菜单,javascript的操作Dom将会变得很繁琐,我们可以应用组合模式来轻松实现。
组合模式用于把一组相似的对象当做一个单一的对象,以树形结构的形式来组合对象,以实现部分和整体的关系。下面的实例通过多级的伸缩菜单实现组合模式,其类图如下:
实现代码:
var Menu = Class.extend({ isLeaf:true, subMenu:[], label:‘菜单‘, href:‘#‘, ctor:function(_label,_href,_isLeaf = true,_subMenu = []){ this.isLeaf = _isLeaf; this.subMenu = _subMenu; this.label = _label; this.href = _href; }, addSubMenu:function(_menu){ this.subMenu.push(_menu); }, toString:function(){ var html = ‘‘; if(!this.isLeaf){ html += ‘<li onclick = "toggleMenu(this)"><a href = "‘ + this.href + ‘">‘+this.label + ‘</a>‘; html += "<ul class = ‘myHide‘>"; for (var i = 0;i < this.subMenu.length ; i++) { html += this.subMenu[i].toString(); } html += ‘</ul>‘; html += ‘</li>‘; }else{ html += ‘<li ><a href = "‘ + this.href + ‘">‘+this.label + ‘</a>‘; html += ‘</li>‘; } return html; } });
<body> <div id="navigation"> <ul id="listUL"> </ul> </div> </body> <script language="javascript"> function toggleMenu(obj){ window.event? window.event.cancelBubble = true : e.stopPropagation(); if(obj.childNodes[1].className == "myHide"){ obj.childNodes[1].className = ‘myShow‘; }else{ obj.childNodes[1].className = ‘myHide‘; } } (function(){ var Home = new Menu("Home","#"); var My = new Menu("My","#",false); var News = new Menu("News","#",false); var My_Info = new Menu("MyInfo",‘#‘,false); var Info_Detail = new Menu("InfoDetail",‘#‘,true); var My_Zone = new Menu("MyZone",‘#‘,true); My_Info.addSubMenu(Info_Detail); My.addSubMenu(My_Info); My.addSubMenu(My_Zone); console.log(document.getElementById("listUL")); document.getElementById("listUL").innerHTML = Home.toString() + My.toString(); })(); </script>
具体的样式可以下载源码查看,实现的效果如图(其实是三层菜单,修改代码可以实现区分开样式):
组合模式最大的缺点是违反了依赖倒置原则。
本文出自 “走一停二回头看三” 博客,请务必保留此出处http://janwool.blog.51cto.com/5694960/1882352
原文地址:http://janwool.blog.51cto.com/5694960/1882352