js獲取元素相對(duì)窗口位置的實(shí)現(xiàn)代碼

字號(hào):


    js獲取元素的offsettop,offsetleft等屬性
    obj.clientwidth //獲取元素的寬度
    obj.clientheight //元素的高度
    obj.offsetleft //元素相對(duì)于父元素的left
    obj.offsettop //元素相對(duì)于父元素的top
    obj.offsetwidth //元素的寬度
    obj.offsetheight //元素的高度
    區(qū)別:
    clientwidth = width + padding
    clientheight = height + padding
    offsetwidth = width + padding + border
    offsetheight = width + padding + border
    offset比client多了border的寬度
    ?123456789101112 //獲取元素的縱坐標(biāo)(相對(duì)于窗口) function gettop(e){ var offset=e.offsettop; if(e.offsetparent!=null) offset+=gettop(e.offsetparent); return offset; } //獲取元素的橫坐標(biāo)(相對(duì)于窗口) function getleft(e){ var offset=e.offsetleft; if(e.offsetparent!=null) offset+=getleft(e.offsetparent); return offset; }
    之前也寫過一篇js關(guān)于獲取元素位置的文章:js獲取元素的offsettop,offsetleft等屬性,我們可以通過offsettop和offsetleft屬性獲取元素相對(duì)窗口的位置,但offsettop和offsetleft屬性都是相對(duì)于父元素定位的,而通常需要獲取位置的元素都不是在最外層,所以遍歷上級(jí)元素的offset相關(guān)屬性少不了。那效率就成問題了。
    ?123456789101112 //獲取元素的縱坐標(biāo)(相對(duì)于窗口) function gettop(e){ var offset=e.offsettop; if(e.offsetparent!=null) offset+=gettop(e.offsetparent); return offset; } //獲取元素的橫坐標(biāo)(相對(duì)于窗口) function getleft(e){ var offset=e.offsetleft; if(e.offsetparent!=null) offset+=getleft(e.offsetparent); return offset; }
    好在瀏覽器給我提供了相應(yīng)的接口getboundingclientrect,這個(gè)方法最早出現(xiàn)在ie瀏覽器中,后來的瀏覽器也跟著支持了這個(gè)方法,而且還更加完善,ie中只能獲取到元素的left,top,bottom,right的屬性,而后面的現(xiàn)代瀏覽器還能獲取到元素的width和
    chrome firefox (gecko) internet explorer opera safari
    1.0 3.0 (1.9) 4.0 (yes) 4.0
    這里要注意的是,bottom是元素底部相對(duì)于窗口頂部的距離,而不是像css里面position的bottom相對(duì)于窗口底部,同理,rihgt屬性是元素最右邊相對(duì)于窗口左邊的距離。
    ?12345678 var box = document.getelementbyid(box); var pos = box.getboundingclientrect(); box.innerhtml = top:+pos.top + left:+pos.left + bottom:+pos.bottom + right:+pos.right + width:+pos.width + height:+pos.height