獲取元素 在網頁中的 坐標


1. 獲取 網頁真實內容 高度

  • // 獲取 網頁真實內容 高度
    function getScrollHeight(){  
        return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);  
    }

     

2. 獲取 網頁真實內容 寬度

  • // 獲取 網頁真實內容 寬度
    function getScrollWidth(){  
        return Math.max(document.body.scrollWidth, document.documentElement.scrollWidth);  
    }

 

3. Element.offsetLeft

  • 當前元素左上角相對於 Element.offsetParent 節點的水平位移,單位為像素

 

4. Element.offsetTop

  • 當前元素左上角相對於 Element.offsetParent 節點的垂直位移,單位為像素

3. 獲取元素 在 網頁 中的 坐標

方法1

  • // 獲取元素 在 網頁 中的 坐標    Test Already.
    function getElementPosition(ele) {
        var left = 0;
        var top = 0;
        var p = ele;
        while (p !== null)  {
            left += p.offsetLeft;
            top += p.offsetTop;
            p = p.offsetParent;   // 遍歷相對元素的坐標
        }
        
        var pageHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
        var pageWidth = Math.max(document.body.scrollWidth, document.documentElement.scrollWidth);
        
        return {
            left: left,
            top: top,
            
            right: pageWidth - left - ele.offsetWidth,
            bottom: pageHeight - top - ele.offsetHeight
        };
    }

 


 方法2

  • // 獲取元素 在 網頁 中的 坐標    Test Already.
    function posInPage(obj){
        var theXOffset = document.documentElement.scrollLeft ||    // 火狐 IE9及以下滾動條是HTML的
                         window.pageXOffset ||                     // IE10及以上 window.pageXOffset
                         document.body.scrollLeft;                 // chrome滾動條是body的
        
        var theYOffset = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
        
        var theClient = obj.getBoundingClientRect();
        
        // 在IE中,默認坐標從(2,2)開始計算,導致最終距離比其他瀏覽器多出兩個像素,需要做以下兼容
        var top2px = document.documentElement.clientTop;
        var left2px = document.documentElement.clientLeft;
        
        var pageHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
        var pageWidth = Math.max(document.body.scrollWidth, document.documentElement.scrollWidth);
        
        return {
            top: theClient.top - top2px + theYOffset,
            left: theClient.left - left2px + theXOffset,
            
            bottom: pageHeight - (theClient.top - top2px + theYOffset) - obj.offsetHeight,
            right: pageWidth - (theClient.left - left2px + theXOffset) - obj.offsetWidth
        };
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM