1. 程式人生 > 實用技巧 >固定導航欄

固定導航欄

<style>
.layui-header{height:60px}
#head-pad{height:60px}
.
fixed-header{position:fixed;top:0;right:0;left:0}
</style>
<div class="layui-header" id="dmt-front-header"></div>

let dmtHead = {
  DMTFRONTHEAD : 'dmt-front-header'
}

//獲取視窗捲去高度
dmtHead.getBrowerScrollTop = function(){
return document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
};

//建立佔位的headPad元素
dmtHead.createHeadPadEl = function(){
return $("<div id='head-pad' style="height:60px"></div>");
};

//固定頭
dmtHead.fixedHead = function(){
let _self = this
,$frontHeader = $("#"+this.DMTFRONTHEAD)
,$headPad = this.createHeadPadEl();
$(window).on('scroll',function(){
if(_self.getBrowerScrollTop()>0){
if(!$frontHeader.hasClass('fixed-header')) {
$frontHeader.addClass('fixed-header');
$frontHeader.before($headPad);
}
}else{
if($frontHeader.hasClass('fixed-header')) {
$headPad.remove();
$frontHeader.removeClass('fixed-header');
}
}
});
};