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

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

    Edit: Add some code to account for the page scrolling.

    function findPos(id) {
        var node = document.getElementById(id);     
        var curtop = 0;
        var curtopscroll = 0;
        if (node.offsetParent) {
            do {
                curtop += node.offsetTop;
                curtopscroll += node.offsetParent ? node.offsetParent.scrollTop : 0;
            } while (node = node.offsetParent);
    
            alert(curtop - curtopscroll);
        }
    }
    

    The id argument is the id of the element whose offset you want. Adapted from a quirksmode post.

提交回复
热议问题