最近在演习原生JS,因而想把几个月之前用jQuery写的一个导航的功用,用原生JS完成一遍。
写JS不到一年,没做IE8兼容,求大神轻喷,有写的不好的,求指教~~
jQuery:
$(".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+):
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);
}