繁体   English   中英

滚动时查找div元素的可见高度

[英]Find visible height of div element while scrolling

请咨询该小提琴http://jsfiddle.net/abhicodes/LasxP/

在这里,我想找出每次滚动时#content-wrapper可见高度。 #header始终具有相同的高度,并且将固定不变,但是某些页面中的页脚高度不同,因此无法将当前页脚高度作为标准。

如果到达页面末尾,则大多数区域都由页脚覆盖,那么我也只希望#content-wrapper的可见部分,其余部分都发生在滚动条中。 对于页脚不可见的页面其余部分,我可以减去页眉高度以得到可见的部分。

假设如果我们在页面底部,并且视口高度为600px,那么我想找出用户可以看到多少#content-wrapper区域。 因为那时还有页脚可容纳100px,页眉可容纳80px,所以#content-wrapper总可见高度将为600-180 = 420px,类似地,如果我们位于顶部,则页脚不存在,仅页眉在那里,因此#content-wrapper可见区域将为520px。

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

尝试

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

这是更新的jsfiddle


逻辑很简单。

  1. 在页脚显示之前使用窗口的高度。
  2. 在显示页脚之后使用页脚的顶部。
  3. [1][2] -标头的高度=您的答案。

以下内容将为您提供可见的高度,并分离出变量,使计算有意义:

$(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/

暂无
暂无

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

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