getting the X and Y coordinates for a div element

前端 未结 5 1810
故里飘歌
故里飘歌 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:34

    By far, the easiest way to get the absolute screen position of an element is getBoundingClientRect.

    var element = document.getElementById('some-id');
    var position = element.getBoundingClientRect();
    var x = position.left;
    var y = position.top;
    // Et voilà!
    

    Keep in mind, though, that the coordinates don’t include the document scroll offset.

    0 讨论(0)
  • 2020-12-17 15:35

    Given the element...

    <div id="abc" style="position:absolute; top:350px; left:190px;">Some text</div>
    

    If the element is in the main document you can get the DIV's coordinates with...

     var X=window.getComputedStyle(abc,null).getPropertyValue('left');
    
     var Y=window.getComputedStyle(abc,null).getPropertyValue('top');
    

    If the element is in an iframe you can get the DIV's coordinates with...

     var X=FrameID.contentWindow.getComputedStyle(abc,null).getPropertyValue('left');
    
     var Y=FrameID.contentWindow.getComputedStyle(abc,null).getPropertyValue('top');
    

    NB: The returned values should be in the format "190px" and "350px".

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-17 15:36

    I think you could use jQuery .offset() http://api.jquery.com/offset/

    0 讨论(0)
  • 2020-12-17 15:50

    You need to find the position using the parent's position too. There's a very good tutorial here: http://www.quirksmode.org/js/findpos.html

    0 讨论(0)
提交回复
热议问题