繁体   English   中英

固定滚动条上的元素,但不知道scrollTop()的位置

[英]Fixed element on scroll without knowing the scrollTop() position

我想在屏幕顶部有一个固定的标题,但不知道scrollTop()位置,因为它是可变的(标题上方有一个可变高度的元素)。

由于offset().top ,我将垂直间距的值保存在一个变量中,问题是当标题固定在顶部时,该值变为0 因此,我无法删除之前添加的课程。

var win = $(window);

win.on('load scroll resize', function(){
    var header  = $('#header-v1'),
        ht      = header.offset().top, // Get the offset from the top
        st      = win.scrollTop(),
        height  = ht - st; // Get the offset from the top of the viewable screen

    var get_h = 1,
        j;

    if (st <= ht) {
        for (j = 0; j < height; j++) {
            get_h += 1;
        }
    } else if (st >= get_h) {
        header.addClass("fixed-nav");

    } else {
        header.removeClass("fixed-nav");
    }

});

我想创建一个计数器来恢复header.offset().top值,因为向下滚动页面后该值为0 我仍然不确定这是否是这样。 有什么建议么?

编辑:下面的代码应该工作。 这是对此的改编。 但是我仍然遇到同样的问题:该类未删除。

var win     = $(window),
    header  = $('#header-v1'),
    ht      = header.offset().top;

win.on('scroll', function(){
    var st      = win.scrollTop();
        ht      = header.offset().top;

    if (st >= ht) {
        header.addClass("fixed-nav");
    } else if (st < ht) {
        header.removeClass("fixed-nav");
    }
});

多亏了jQuery函数one()我可以自己修复它。

var win     = $(window),
    header  = $('#header-v1');
    var ht;

// Get the offset from the top into another scroll event
// ... using the function "one()".
win.one('scroll', function(){
    ht  = header.offset().top;
});

win.on('scroll', function(){
    var st = win.scrollTop();
    if (st >= ht) {
        header.addClass("fixed-nav");
    } else if (st < ht) {
        header.removeClass("fixed-nav");
    }
});

实际上,在header上方,我有一个带有按钮的slideToggle()栏,该按钮使用slideToggle()函数显示更多内容。 因此,每次单击后从顶部开始的高度都会发生变化(显示/隐藏高度可变的内容),这是解决方案:

win.on("load resize",function(){
    // Get the offset
    win.one('scroll', function(){
        ht  = header.offset().top;
    });

    $(".navbtn").toggle(function() {
        // The user clicks to show more content, get the offset again
        win.one('scroll', function(){
            ht  = header.offset().top;
        });
    }, function () {
        // Get the offset again when the content is hidden
        win.one('scroll', function(){
            ht  = header.offset().top;
        });
    });
});

代码在这里运行: jsfiddle 尝试改变的高度topbar的CSS,看看如何在menu的顶部使用所确定的偏移固定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM