(function($) {
var DNG = {};
//----------------------------------------------------/
// 相對父級元素fixed
//----------------------------------------------------/
DNG.parentFixed = function() {
// 得到須要fixed定位的元素
var el =$(".parent-fixed");
// 判斷是否存在
if( el.length > 0){
el.each(function(){
let $this = $(this);
// 輸入header爲absolute或fixed定位的高度
var headerFixed = 50 ;
// 得到元素相關數據
function getdata(ele){
// 獲取父級元素 父級元素定位 父級元素高度
ele.parentOffset = ele.offsetParent();
ele.parentOffsetY = ele.parentOffset.offset().top - headerFixed;
ele.parentHeight = ele.parentOffset.height();
// 獲取元素定位 元素高度
ele.oldPositionY = ele.positionY = ele.position().top;
ele.Height = ele.height();
// 計算元素滑動最大值 = 父級元素定位 + 父級元素高度 - 元素定位 - 元素高度
ele.maxScroll = ele.parentOffsetY + ele.parentHeight - ele.positionY - ele.Height;
return ele;
}
$this = getdata($this);
// 窗口改變觸發事件
$(window).resize(function(){
// 更新元素相關數據
$this = getdata($this);
});
// 滑動觸發事件
$(window).scroll(function(){
$this.Scroll = $(window).scrollTop();
// 判斷1:小於父級元素定位
// 判斷2:大於父級元素定位,小於滑動最大範圍
// 判斷3:大於滑動最大範圍
if( $this.Scroll < $this.parentOffsetY ){
$this.positionY = $this.oldPositionY;
} else if( $this.Scroll >= $this.parentOffsetY && $this.Scroll <= $this.maxScroll ){
// 計算元素Top定位,滑動距離 - 父級元素定位 + 元素定位
$this.positionY = $this.Scroll - $this.parentOffsetY + $this.oldPositionY;
} else{
$this.positionY = $this.maxScroll - $this.parentOffsetY + $this.oldPositionY;
}
// 改變元素定位
$this.css("top",$this.positionY);
});
});
}
};
//----------------------------------------------------/
// end
//----------------------------------------------------/
$(document).ready(function() {
DNG.parentFixed();
});
})(jQuery);