下拉菜单的jquery组件封装
程序员文章站
2022-04-14 13:57:08
首先晒出封装好的dropdown.js (function($){ 'use strict';//使用严格模式 //构造函数形式 function Dropdown(elem,options){ //保存到this中才能公用 this.elem=elem; this.options=options; ......
首先晒出封装好的dropdown.js
(function($){ 'use strict';//使用严格模式 //构造函数形式 function dropdown(elem,options){ //保存到this中才能公用 this.elem=elem; this.options=options; this.timer=null; this.list=this.elem.find(".dropdown-list");//下拉列表是需要动画的部分 this.activeclass=options.active+"-active"; this._init();//初始化 } dropdown.defaults={ event:"hover",//还有click css3:false, js:false, animation:"fade", delay:0,//默认无延迟 active:"dropdown" }; //约定俗称:内部使用的可以以_开头 dropdown.prototype._init=function(){ var self=this; //指定动画模式 this.list.showhide(this.options); //绑定事件 this.list.on("show shown hide hidden",function(e){ //console.log(e.type); //消息转发 self.elem.trigger("dropdown-"+e.type);//触发事件 }); if(this.options.event==="click"){ this.elem.click(function(e){ self.show(); e.stoppropagation();//阻止冒泡,否则点击下拉时也会冒泡到document,导致显示后立刻隐藏的效果 }); //点击空白处消失 $(document).click($.proxy(this.hide,this)); }else{//容错机制,写错默认也是hover this.elem.hover($.proxy(this.show,this),$.proxy(this.hide,this)); } }; dropdown.prototype.show=function(){ var self=this; if(this.options.delay){ //如果有延迟 this.timer=settimeout(function(){ _show(); },this.options.delay); }else{ //没有延迟 _show(); } function _show(){ self.elem.addclass(self.activeclass); self.list.showhide("show");//show } } dropdown.prototype.hide=function(){ if(this.options.delay){ cleartimeout(this.timer); } this.elem.removeclass(this.activeclass); this.list.showhide("hide");//show } //插件形式 $.fn.extend({ dropdown:function(opt){ return this.each(function(){ var ui=$(this); var dropdown=ui.data("dropdown"); //opt是参数对象 var options=$.extend({},dropdown.defaults,ui.data(),typeof opt==="object"&&opt); //单例:一个dom元素对应一个实例,如果已经存在则不需要反复实例化 if(!dropdown){ dropdown=new dropdown(ui,options); ui.data("dropdown",dropdown); } //opt是show或者hide if(typeof dropdown[opt]==="function"){ dropdown[opt](); } }); } }); })(jquery); //为了防止$符发生冲突,将jquery作为参数传入,则$符作为内部变量,不会发生冲突
使用方法:
在页面中引入base.css
transition.js
showhide.js
dropdown.js (上面刚贴的)
然后上代码:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>dropdown</title> <link rel="stylesheet" href="../css/base.css"> <style> /*分离出dropdown公共样式*/ .dropdown{ position: relative; } .dropdown-toggle{ position: relative; z-index:2; } .dropdown-arrow{ display: inline-block; vertical-align: middle; background-repeat: no-repeat; } .dropdown-list{ display: none; position: absolute; z-index:1; } .dropdown-left{ left:0; right:auto; } .dropdown-right{ right:0; left:auto; } /*分离出nav的dropdown独有样式*/ .menu .dropdown-toggle{ display: block; padding:0 16px 0 12px; border-right:1px solid #f3f5f7; border-left:1px solid #f3f5f7; } .menu .dropdown-arrow{ margin-left:8px; vertical-align: middle; } .menu .dropdown-list{ border:1px solid #cdd0d4; background-color: #fff; top:100%; overflow:hidden;/*避免容器还没显示时,文字提前显示*/ } .menu-item{ height:30px; line-height:30px; padding:0 12px; white-space: nowrap; } /*鼠标移入*/ .menu-item:hover{ background-color: #f3f5f7; } .menu-active .dropdown-toggle{ color:#f01414; background-color:#fff; border-color:#cdd0d4; } @font-face { font-family: "iconfont"; src: url('../font/iconfont.eot?t=1582272973653'); /* ie9 */ src: url('../font/iconfont.eot?t=1582272973653#iefix') format('embedded-opentype'), /* ie6-ie8 */ url('data:application/x-font-woff2;charset=utf-8;base64,d09gmgabaaaaaamgaasaaaaabxaaaalraaeaaaaaaaaaaaaaaaaaaaaaaaaaaaaaheigvgcdbgqbbifbatycjammcwgabcafhg0hqrssbsgekiscccfeunlxeqbaphzt93ru7n5elurbcr2br5bliy51gkpgvnycg9xxbmsbd+4zpscmogtu9sct57/89mab8gdg+u2hmjtwk9plaolpn+dyehpoqo6qb1lua9ny4/lrl8a4oedhgrqiciqgt0f2r6cwvjta25ik3ngapi7gonagbekolplaprrrfcnffootm4t4zvezpunf8cr+fvy3m1xiapkz8vi1agso+zx5vzfnqjvdiug9navspdi2awpxttvznr2qohttk0n/ev0r0llxqijwmzb6qf94iahzartgpc0mfvn7cojffxdiiim6co4btln2+u4swkuugck7xzpwn03hfqhrbfzkhnd9n/pz4f7p9ffhg8fc2vs3r7pmkloez8huotvxoydrarz8tpzojtanhtbflfnt8m1kb0r92n/hum2pejfy0bcssn9up2u/iqlrdf15exnd72h3elit35f1brwj/n/utxkjpdzjbd/wyyyk987lmn+ix9xy6sqya1d9yb9yeqdktvt2m3/jys3h8+ig6f+zu8bp8933ofl9khbl8yammvh5u9vgqzg1jjuxxewrbf+2/qzdcvrxrsujjp2zbpnbtysmwy6kyrfz0zjz2m2o6dinuqydanukdn7hbguvsgsblrkeozdi+j4jg/pofvy3aub+om4y9mg7g/4rdqyg7fzjec+qby5pq1kgbvbszc2p70ciqfg0qi35hkrtchymp6rv87xiqhsjmbyjmymxddeloqwh+yfni9bkiyieliixzi1itcvtd0oria7cheehpaaxgmzng2qcwodd1oxb7fmdejfjw6m9oozid4syktuh0qvia8hakwgjhuuemwmidaydqrhf6kaa0g3raaji2t5ngqiyfnkelfwbvlczrk0p21v0/9sgbc7kovlkkjrxitlpchlymjj5jvecmomrewaaaaa=') format('woff2'), url('../font/iconfont.woff?t=1582272973653') format('woff'), url('../font/iconfont.ttf?t=1582272973653') format('truetype'), /* chrome, firefox, opera, safari, android, ios 4.2+ */ url('../font/iconfont.svg?t=1582272973653#iconfont') format('svg'); /* ios 4.1- */ } .iconfont { font-family: "iconfont" !important; font-size: 14px; font-style: normal;/*i标签自带斜体效果*/ -webkit-font-smoothing: antialiased;/*在webkit内核和火狐浏览器中,抗锯齿*/ -moz-osx-font-smoothing: grayscale; } [class*="-active"] .dropdown-arrow{ -webkit-transform:rotate(180deg); -moz-transform:rotate(180deg); -ms-transform:rotate(180deg); -o-transform:rotate(180deg); transform:rotate(180deg); } /*提取出过渡样式,可公用*/ .transition{ -webkit-transition:all .5s; -moz-transition:all .5s; -ms-transition:all .5s; -o-transition:all .5s; transition:all .5s; } /*showhide组件的样式*/ .fadeout{ opacity: 0; visibility: hidden; } /*收缩样式*/ .slideupdowncollapse{ height:0 !important;/*避免因为优先级不够而无法生效*/ padding-top:0 !important; padding-bottom:0 !important; } .slideleftrightcollapse{ width:0 !important;/*避免因为优先级不够而无法生效*/ padding-left:0 !important; padding-right:0 !important; } .dropdown-loading{ width:32px; height:32px; background:url(../img/loading.gif) no-repeat; margin:20px; } </style> </head> <body> <!-- 用data-load来确定数据源 --> <div class="menu dropdown fl" data-active="menu" data-load="dropdown.json"> <a href="javascript:;" class="dropdown-toggle">我的慕淘<i class="dropdown-arrow iconfont transition"></i></a> <ul class="dropdown-list dropdown-left"> <li class="dropdown-loading"></li> </ul> </div> <div class="menu dropdown fl" data-active="menu"> <a href="javascript:;" class="dropdown-toggle">我的慕淘<i class="dropdown-arrow iconfont transition"></i></a> <ul class="dropdown-list dropdown-left"> <li class="menu-item"><a href="#">已买到的宝贝</a></li> <li class="menu-item"><a href="#">我的足迹</a></li> </ul> </div> <button class="show-btn">点我显示</button> <button class="hide-btn">点我隐藏</button> <script src="../js/jquery.js"></script> <script src="../js/transition.js"></script> <script src="../js/showhide.js"></script> <script src="../js/dropdown.js"></script> <script> //绑定事件 显示之前加载数据 $(".dropdown").on("dropdown-show",function(e){ var ui=$(this); var dataload=ui.data("load"); if(!dataload) return; //只请求一次即可 if(!ui.data("loaded")){ var list=ui.find(".dropdown-list"); var html=""; //$.getjson(文件,回调) jquery封装的获取json数据的方法 settimeout(function(){ $.getjson(dataload,function(data){ //console.log(data); for(var i=0;i<data.length;i++){ console.log(data[i]); html+='<li class="menu-item"><a href="'+data[i]["url"]+'">'+data[i]["name"]+'</a></li>'; } //console.log(html); list.html(html); ui.data("loaded",true); }); },500);//模拟线上延迟 } }); //指定参数 $(".dropdown").dropdown({ event:"hover", css3:true, js:true, animation:"slideupdown" }); //通过按钮也可以控制下拉菜单的显示隐藏 $(".show-btn").on("click",function(){ $(".dropdown").dropdown("show"); }); $(".hide-btn").on("click",function(){ $(".dropdown").dropdown("hide"); }); </script> </body> </html>
这块区域是按需加载的过程,设置的是页面第一次加载时,下拉菜单的项没有加载
等到用户将鼠标移入时,通过ajax请求获取数据加载进来
这是dropdown.json数据的结构:
[ { "url":"#", "name":"已买到的宝贝" }, { "url":"#", "name":"我的足迹" }, { "url":"#", "name":"我的优惠券" } ]
效果图
上一篇: jquery如何判断鼠标是否在当前div上,实战方法
下一篇: 带输入提示的搜索框ajax请求