2 獲取元素在頁面中的位置

獲取元素在頁面中的位置
絕對位置:到body的距離
相對位置:到視口的距離


自己定位爲fixed
==> offsetParent:null(不是火狐)
offsetTop和offsetLeft也是參照於body的
==> offsetParent:body(火狐)
自己定位不爲fixed
父級沒有定位
==> offsetParent:body
父級有定位
==> offsetParent:定位父級javascript

function getPointAb(node){
                //while循環疊加offsetParent的offsetTop和offsetLeft
                var x =0;
                var y = 0;
                while(node){
                    x+=node.offsetLeft;
                    y+=node.offsetTop;
                    
                    node = node.offsetParent;
                }
                
                return {x:x,y:y};
            }
封裝函數
<!DOCTYPE html>
<html id="html">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            *{
                margin: 0;
                padding: 0;
            }
            html,body{
                height: 100%;
                overflow: hidden;
            }
            #wrap{position: absolute;background: pink;left: 200px;top: 200px;}
            #inner1{position: absolute;background: deeppink;left: 150px;top: 150px;}
            div{
                width: 200px;
                height: 200px;
            }
        </style>
    </head>
    <body id="body" >
        <div id="wrap">wrap
            <div id="inner1">
                inner1
            </div>
        </div>
    </body>
    <script type="text/javascript">
        /*
         獲取元素在頁面中的位置
            絕對位置:到body的距離
            相對位置:到視口的距離
            
            
            自己定位爲fixed
                    ==> offsetParent:null(不是火狐)
                            offsetTop和offsetLeft也是參照於body的
                    ==> offsetParent:body(火狐)
            自己定位不爲fixed
                    父級沒有定位
                        ==> offsetParent:body
                    父級有定位
                        ==> offsetParent:定位父級
            
            
        */
        window.onload=function(){
            var inner1 = document.querySelector("#inner1");
            var point = getPointAb(inner1);
            console.log(point);
            
            
            //boder margin會影響這個函數的取值
            function getPointAb(node){
                //while循環疊加offsetParent的offsetTop和offsetLeft
                var x =0;
                var y = 0;
                while(node){
                    x+=node.offsetLeft;
                    y+=node.offsetTop;
                    
                    node = node.offsetParent;
                }
                
                return {x:x,y:y};
            }
        }
    </script>
</html>
View Code

 




*/css

相關文章
相關標籤/搜索