Using jquery to get element's position relative to viewport

前端 未结 6 1255
囚心锁ツ
囚心锁ツ 2020-12-07 08:09

What\'s the proper way to get the position of an element on the page relative to the viewport (rather than the document). jQuery.offset function seemed promising:

6条回答
  •  被撕碎了的回忆
    2020-12-07 08:45

    Here are two functions to get the page height and the scroll amounts (x,y) without the use of the (bloated) dimensions plugin:

    // getPageScroll() by quirksmode.com
    function getPageScroll() {
        var xScroll, yScroll;
        if (self.pageYOffset) {
          yScroll = self.pageYOffset;
          xScroll = self.pageXOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {
          yScroll = document.documentElement.scrollTop;
          xScroll = document.documentElement.scrollLeft;
        } else if (document.body) {// all other Explorers
          yScroll = document.body.scrollTop;
          xScroll = document.body.scrollLeft;
        }
        return new Array(xScroll,yScroll)
    }
    
    // Adapted from getPageSize() by quirksmode.com
    function getPageHeight() {
        var windowHeight
        if (self.innerHeight) { // all except Explorer
          windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) {
          windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
          windowHeight = document.body.clientHeight;
        }
        return windowHeight
    }
    

提交回复
热议问题