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

后端 未结 12 1117
你的背包
你的背包 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:33

    function inViewport(element) {
        let bounds = element.getBoundingClientRect();
        let viewWidth = document.documentElement.clientWidth;
        let viewHeight = document.documentElement.clientHeight;
    
        if (bounds['left'] < 0) return false;
        if (bounds['top'] < 0) return false;
        if (bounds['right'] > viewWidth) return false;
        if (bounds['bottom'] > viewHeight) return false;
    
        return true;
    }
    

    source

提交回复
热议问题