getting the X and Y coordinates for a div element

前端 未结 5 1824
故里飘歌
故里飘歌 2020-12-17 14:55

I\'ve been trying to make a javascript to get a X and Y coordinates of a div element. After some trying around I have come up with some numbers but I\'m not sur

5条回答
  •  难免孤独
    2020-12-17 15:36

    Here a simple way to get various information regarding the position of a html element:

            var my_div = document.getElementById('my_div_id');
            var box = { left: 0, top: 0 };
            try {
                box = my_div.getBoundingClientRect();
            } 
            catch(e) 
            {}
    
            var doc = document,
                docElem = doc.documentElement,
                body = document.body,
                win = window,
                clientTop  = docElem.clientTop  || body.clientTop  || 0,
                clientLeft = docElem.clientLeft || body.clientLeft || 0,
                scrollTop  = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop  || body.scrollTop,
                scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
                top  = box.top  + scrollTop  - clientTop,
                left = box.left + scrollLeft - clientLeft;
    

提交回复
热议问题