[jQuery]相对父级元素的fixed定位

(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);
posted @ 2018-03-17 20:24  阳癫疯  阅读(1032)  评论(1编辑  收藏  举报