jQuery code to change position of element on scroll

后端 未结 2 894
时光取名叫无心
时光取名叫无心 2021-02-10 21:51

I have a bar which includes sharing and social icons. The bar is positioned below post title now like this:

2条回答
  •  一向
    一向 (楼主)
    2021-02-10 22:06

    Here is the fixed solution. :)

    It starts with getting scroll position then change the CSS of element to fixed when scrolling passes specific value (the distance between top to element start) else revert default css for element.

    var sOffset = $(".sharelinks").offset().top;
    var shareheight = $(".sharelinks").height() + 43;
    $(window).scroll(function() {
        var scrollYpos = $(document).scrollTop();
        if (scrollYpos > sOffset - shareheight) {
            $(".sharelinks").css({
                'top': '61px',
                'position': 'fixed'
            });
        } else {
            $(".sharelinks").css({
                'top': 'auto',
                'position': 'relative'
            });
        }
    });
    

提交回复
热议问题