滚动元素底部时触发事件? [英] Trigger event when scroll past bottom of element?

查看:90
本文介绍了滚动元素底部时触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在我的网站上,我在网站的最顶端有一个静态标题 - 它并不固定在视口的顶部。但是,我想要做的是一旦用户滚动过这个div的底部,就会出现一个固定的导航栏。我的代码几乎可以工作,但只触发div顶部的偏移量,这是页面的顶部。这是我的代码:

So on my website I have a static header at the very top of the site -- it's not fixed to the top of the viewport. However, what I'd like to do is once the user scrolls past the bottom of this div, for a fixed navbar to appear. My code almost works, but only triggers at the top offset of the div, which is the very top of the page. Here's my code:

$("#header-2").hide(); // hide the fixed navbar initially

var topofDiv = $("#header-container").offset().top; //gets offset of header
$(window).scroll(function(){
    if($(window).scrollTop() > topofDiv){
       $("#header-2").show();
    }
    else{
       $("#header-2").hide();
    }
});

同样,我需要触发显示固定的导航栏,一旦用户滚动到<$ c的底部$ c>#header-container ,而不是现在的顶端。帮助?

Again, I need to trigger showing the fixed navbar once the user scrolls past the bottom of #header-container, not the top like it does now. Help?

推荐答案

我认为如果您将div的高度添加到顶部偏移量,您将得到您想要的行为

I think that if you add the height of the div to the top offset you'll get the behaviour you want

$("#header-2").hide(); // hide the fixed navbar initially

var topofDiv = $("#header-container").offset().top; //gets offset of header
var height = $("#header-container").outerHeight(); //gets height of header

$(window).scroll(function(){
    if($(window).scrollTop() > (topofDiv + height)){
       $("#header-2").show();
    }
    else{
       $("#header-2").hide();
    }
});

这篇关于滚动元素底部时触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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