首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找div顶部和窗口底部之间的高度。

问查找div顶部和窗口底部之间的高度。
EN

Stack Overflow用户
提问于 2014-10-28 22:51:07
回答 1查看 3.9K关注 0票数 0

使用jQuery,如何找到任何div顶部和视口底部之间的高度?

在我的代码中,我需要在滚动时主动地找到页脚顶部和窗口底部之间的距离。

知道怎么做吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-28 23:15:29

一个简单的方法:

代码语言:javascript
复制
function updateScroll () {
    // the div whose offset we're measuring:
    var measure = $('#measure'),
    // the height of the window:
        windowHeight = $(window).height(),
    // the scroll-distance of the window:
        scrollDistance = $(window).scrollTop(),
    // how far from the 'top' of the document the div element is:
        divOffsetTop = measure.offset().top,
    // scrollDistance + windowHeight gives measures how far from the 'top'
    // of the document the bottom of the viewport is, subtracting that from
    // the offset of the div gives the difference. I used Math.Abs() because
    // I didn't know if you wanted to know *just* how far, or if you
    // wanted to know if it was 'above' (-difference) or 'below' (+ difference)
    // the bottom of the viewport:
        delta = Math.abs(divOffsetTop - (scrollDistance + windowHeight));

    // setting the text of the div itself, you may want to put that someplace
    // else:
    $('#distance').text(delta + 'px');
}

// binding the function to the scroll event:
$(window).scroll(updateScroll);

JS Fiddle演示。

参考文献:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26619895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档