Responsive scrolltop

给你一囗甜甜゛ 提交于 2019-12-22 01:19:05

问题


Im using the following code to detect when an object should become 'sticky' and stay fixed in its content.

var $window = $(window),
    $stickyEl = $('#single-post-details'),
    elTop = $stickyEl.offset().top;

$window.scroll(function() {
    $stickyEl.toggleClass('sticky', $window.scrollTop() + 52 > elTop);
});

However I would like to make this responsive. This means that somehow it needs to detect the height of the banner above it first so that it doesn't trigger at the wrong point.. Here is a fiddle with as an example.


回答1:


The problem is that on the resize, the top position of you sticky element change. To solve that, you should not check the height of the image, but recalculate the top position.

The use of .resize event is usefull here. On the callback, just update you global variable :

var $window = $(window),
    $stickyEl = $('#single-post-details'),
    elTop = $stickyEl.offset().top;

$window.on({
    resize : function(){
        elTop = $stickyEl.offset().top;
        $window.trigger('scroll');
    },
    scroll : function() {
        $stickyEl.toggleClass('sticky', $window.scrollTop() + 20 > elTop);
    }
});

Note: the trigger('scroll') is important to prevent the sticky element to go over the image while expanding the window.

Fiddle



来源:https://stackoverflow.com/questions/25975011/responsive-scrolltop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!