How to get an element's top position relative to the browser's viewport?

后端 未结 12 1202
你的背包
你的背包 2020-11-29 17:17

I want to get the position of an element relative to the browser\'s viewport (the viewport in which the page is displayed, not the whole page). How can this be done in JavaS

12条回答
  •  误落风尘
    2020-11-29 17:38

    The function on this page will return a rectangle with the top, left, height and width co ordinates of a passed element relative to the browser view port.

        localToGlobal: function( _el ) {
           var target = _el,
           target_width = target.offsetWidth,
           target_height = target.offsetHeight,
           target_left = target.offsetLeft,
           target_top = target.offsetTop,
           gleft = 0,
           gtop = 0,
           rect = {};
    
           var moonwalk = function( _parent ) {
            if (!!_parent) {
                gleft += _parent.offsetLeft;
                gtop += _parent.offsetTop;
                moonwalk( _parent.offsetParent );
            } else {
                return rect = {
                top: target.offsetTop + gtop,
                left: target.offsetLeft + gleft,
                bottom: (target.offsetTop + gtop) + target_height,
                right: (target.offsetLeft + gleft) + target_width
                };
            }
        };
            moonwalk( target.offsetParent );
            return rect;
    }
    

提交回复
热议问题