最近在練習原生JS,因而想把幾個月以前用jQuery寫的一個導航的功能,用原生JS實現一遍。css
寫JS不到一年,沒作IE8兼容,求大神輕噴,有寫的很差的,求指教~~ide
jQuery:this
$(".navigation li").addClass("displayNone"); $(".nav_icon").click(function(){ open_nav(); return false; }); $(window).click(function(){ close_nav(); }); function open_nav(){ $(".navigation").removeClass("displayNone"); $(".navigation").css("visibility","hidden"); $(".navigation li").each(function(i){ var nav_li = $(this); setTimeout(function(){ nav_li.slideDown("fast"); },100+100*i); }); $(".navigation").css("visibility","visible"); } function close_nav(){ var li_count = $(".navigation li").length; $(".navigation li").each(function(i){ var nav_li = $(this); setTimeout(function(){ nav_li.slideUp("fast"); },100*li_count-100*i); }); }
native JS (IE9+):code
var Navigation = function(){ var el = this.el = document.getElementsByClassName("navigation")[0]; var getCurrentHeight = function(){ if(window.getComputedStyle){ return window.getComputedStyle(el,null).height; }else if(el.currentStyle){ return el.currentStyle.height; }else{ return el.offsetHeight; } }; var navHeight = parseInt(getCurrentHeight()); this.openList = function(speed){ //speed爲展開用時 el.style.visibility = "visible"; var currentHeight = document.getElementsByClassName("navigation")[0].style.height = 0; var openTimer = setInterval(function(){ currentHeight += navHeight*(10/speed); el.style.height = currentHeight + "px"; if(currentHeight >= navHeight){ el.style.height = navHeight + "px"; clearInterval(openTimer); } },10); navStatus ++; }; this.closeList = function(speed){ //speed爲收起用時 var currentHeight = parseInt(getCurrentHeight()) ; var closeTimer = setInterval(function(){ currentHeight -= navHeight*(10/speed); el.style.height = currentHeight + "px"; if(currentHeight <= 0){ el.style.height = "0px"; clearInterval(closeTimer); } },10); navStatus = 0; }; } var navigation = new Navigation(); var navStatus = 0; document.getElementsByClassName("nav_icon")[0].onclick = function(e){ if(navStatus == 0){ navigation.openList(450); window.event ? window.event.cancelBubble = true : e.stopPropagation(); }else{ navigation.closeList(450); } } window.onclick = function(){ navigation.closeList(450); }