【问题标题】:Find visible height of div element while scrolling滚动时查找 div 元素的可见高度
【发布时间】:2013-08-03 13:52:15
【问题描述】:

请参考这个小提琴http://jsfiddle.net/abhicodes/LasxP/

在这里我想找出每次滚动时#content-wrapper 的可见高度。 #header 将始终具有相同的高度并且它会被固定,但我的某些页面的页脚高度不同,所以我不能以当前页脚高度作为标准。

如果我到达页面的末尾,那么大部分区域都被页脚覆盖,那么我也只想要#content-wrapper 的可见部分,并且在滚动的其余部分也会发生同样的情况。对于页脚不可见的页面的其余部分,我可以减去页眉高度以获得可见部分。

假设如果我们位于页面底部并且视口高度为 600 像素,那么我想知道用户可以看到 #content-wrapper 的多少区域。因为那时页脚也在那里,它可以容纳 100 像素,而页眉可以容纳 80 像素,所以#content-wrapper 的总可见高度将是 600-180 = 420 像素,同样,如果我们在顶部,那么页脚不存在,而只有页眉存在,所以#content-wrapper 的可见区域为 520px。

所以,故事的寓意是,如果您考虑到这个小提琴,我想在滚动期间的任何给定实例中找出#content-wrapper 的高度对用户可见

【问题讨论】:

  • 我认为你需要做更多的工作来明确地指定你想要发生的事情。目前,我无法说出你想要达到的目标。
  • @Abhi 这是您正在寻找的#content-wrapper 可见区域的输出吗,请访问link
  • @Sumurai8:我已经解决了这个问题,但它没有解决我的问题。那里的答案没有提供视口中可见的 div 高度

标签: javascript jquery html css


【解决方案1】:

以下将为您提供可见高度,并将变量分开,以便计算有意义:

$(document).on('scroll', function() {
    //Container
    var cont = $("#content-container");

    //Scroll Position (varies with scroll)
    var pageTop = $(document).scrollTop();
    //Visible Page Size (fixed)
    var pageSize = $(window).height();

    //Header Height (fixed)
    var headerHeight = $('#header').height();

    //Content top (fixed)
    var contTop = cont.offset().top;
    //Content top position (varies with scroll)
    var contTopPos = contTop - pageTop;
    //Content bottom (fixed)
    var contBottom =  cont.height() + contTop;
    //Content position in relation to screen top (varies with scroll)
    var contBottomPos = contBottom - pageTop;

    /*
        VISIBLE AREA
        Take the size of screen/page, unless the bottom of the content further up
            and subtract from it
        The header height, unless the top of the content is below the header
    */
    var visibleArea = Math.min(pageSize, contBottomPos) - Math.max( headerHeight, contTopPos);
});

示例:http://jsfiddle.net/asifrc/LasxP/8/

【讨论】:

    【解决方案2】:

    试试

    var $win = $(window);
    var $footer = $("#footer");
    $(window).scroll(function(){
        var windowHeight = $win.height();
        var footerTop = $footer.offset().top - $win.scrollTop();
        var visibleHeight = Math.min(windowHeight, footerTop) - 80;
        console.log(windowHeight +", " + footerTop + ", " + visibleHeight);
    });
    

    Here is the updated jsfiddle.


    逻辑很简单。

    1. 在页脚显示之前使用窗口的高度。
    2. 在页脚变得可见后使用页脚顶部。
    3. [1][2] - 标题的高度 = 你的答案。

    【讨论】:

    • 使用的函数/方法的链接:scrollTopoffsetheight
    • 谢谢,我从早上就被困在这上面了。我在 stackoverflow 上找到的所有类似问题的正确答案
    • @Abhi 很高兴能帮上忙。 @Sumurai8 感谢您的链接。
    猜你喜欢
    • 2019-03-22
    • 2017-03-24
    • 1970-01-01
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2023-04-02
    相关资源
    最近更新 更多