响应式scrolltop [英] Responsive scrolltop

查看:79
本文介绍了响应式scrolltop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码来检测对象何时应变为粘性并在其内容中保持固定。

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.

推荐答案

问题是在调整大小时,粘性元素变化的最高位置。要解决这个问题,你不应该检查图像的高度,而是重新计算顶部位置。

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.

使用 .resize 事件在这里很有用。在回调中,只需更新全局变量:

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);
    }
});

注意: 触发器('scroll' )对于防止粘性元素在展开窗口时越过图像非常重要。

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

这篇关于响应式scrolltop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆