简体   繁体   English

关于视口的元素位置

[英]Element position with respect to viewport

I am trying to calculate an element's position with respect to viewport(above, below or in viewport) : 我正在尝试计算元素相对于视口的位置(在视口上方,下方或视口中):

    var viewportBottom = function () {
            return window.pageYOffset;
        },
        viewportTop = function () {
            return window.pageYOffset - window.innerHeight;
        },
        elementTop = function ($e) {
            return $e.offset().top - $e.height();
        },
        elementBottom = function ($e) {
            return elementTop($e) + $e.height();
        };


var aboveViewport = viewportTop() > elementBottom(this.$e),
        belowViewport = viewportBottom() < elementTop(this.$e),
        inViewport = !aboveViewport && !belowViewport;

This calculates correctly only as long as the element's height is same as viewport. 只要元素的高度与视口相同,这只能正确计算。 What am i missing ? 我错过了什么?

This api worked for me : getBoundingClientRect , It is specifically provided for evaluating the position with respect to viewport. 这个api对我有用getBoundingClientRect ,它专门用于评估相对于视口的位置。

Here is what I ended up doing: 这是我最终做的事情:

var container     = element.getBoundingClientRect(),
    aboveViewport = (container.top  + container.height) < 0 ,
    belowViewport = container.top > $(window).height(),
    inViewport    = !aboveViewport && !belowViewport,

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

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