简体   繁体   English

使用javascript,如何得到一个元素的position

[英]Using javascript, how to get the position of an element

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.就像标题说的那样,如何获取元素的 x、y 位置相对于它们在 web 页面中的位置以及它们的定位方案,如绝对、相对等。

In a modern browser, getBoundingClientRect and getClientRects will give you rect objects describing your element.在现代浏览器中,getBoundingClientRect 和 getClientRects 将为您提供描述元素的 rect 对象。 See https://developer.mozilla.org/en/DOM/element.getBoundingClientRect and https://developer.mozilla.org/en/DOM/element.getClientRects请参阅https://developer.mozilla.org/en/DOM/element.getBoundingClientRecthttps://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 (eg object-detect getBoundingClientRect and fall back on some other method if it's not present).如果您必须使用 IE8,那么您必须在不同的浏览器中执行不同的操作才能获得正确的答案(例如,对象检测 getBoundingClientRect 并在不存在时使用其他方法)。

The jQuery offset() calculation and the Quirksmode findPos will give incorrect answers in any browser that does subpixel positioning (eg Firefox or IE9), because they will round the answer to an integer number of pixels. jQuery offset()计算和 Quirksmode findPos将在任何进行亚像素定位的浏览器(例如 Firefox 或 IE9)中给出不正确的答案,因为它们会将答案四舍五入为像素数为 Z157DB7DF530023575515ZD366C。 Depending on what you're doing, that may or may not be ok.取决于你在做什么,这可能会也可能不会。

With jQuery:使用 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 :如果没有 jQuery,请使用Quirksmode 的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 .在没有库的情况下获取计算的 CSS position值是另一种蠕虫 It boils down to:它归结为:

Check out this看看这个

JS: 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: HTML:

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

RETURN CALL:回电:

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

I hope its help to you我希望它对你有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM