Using javascript, how to get the position of an element

Deadly 提交于 2019-12-10 21:44:11

问题


like the title says, how to get the element's x, y positions with respect to their location in the web page and their positioning schemes like absolute, relative etc.


回答1:


In a modern browser, getBoundingClientRect and getClientRects will give you rect objects describing your element. See https://developer.mozilla.org/en/DOM/element.getBoundingClientRect and https://developer.mozilla.org/en/DOM/element.getClientRects

If you have to work with IE8, then you'll have to do different things in different browsers to get correct answers (e.g. object-detect getBoundingClientRect and fall back on some other method if it's not present).

The jQuery offset() calculation and the Quirksmode findPos will give incorrect answers in any browser that does subpixel positioning (e.g. Firefox or IE9), because they will round the answer to an integer number of pixels. Depending on what you're doing, that may or may not be ok.




回答2:


With jQuery:

var $elt = $('select an element however'),
    cssPosition = $elt.css('position'),
    offset = $elt.offset(),
    top = offset.top,
    left = offset.left;

Without jQuery, use Quirksmode's findPos function:

var elt = document.getElementBy...,
    pos = findPos(elt),
    top = pos[1],
    left = pos[0];

Getting the computed CSS position value without a library is another can of worms. It boils down to:

  • element.currentStyle (IE)
  • getComputedStyle(element) (real browsers)



回答3:


Check out this

JS:

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}

HTML:

<div id="ser">&nbsp;TEST</div>

RETURN CALL:

alert(findPos(document.getElementById('ser')));

I hope its help to you



来源:https://stackoverflow.com/questions/6146027/using-javascript-how-to-get-the-position-of-an-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!