简体   繁体   English

JavaScript获取div的绝对位置

[英]Javascript get absolute position of a div

I have a div (oCell) created at runtime using javascript. 我在运行时使用JavaScript创建了一个div(oCell)。

I then want to position another independant div (random-div) relative to this div. 然后,我想相对于该div定位另一个独立的div(随机div)。 For reasons within the program random-div has to be positioned absolutely and oCell relatively. 由于程序内的原因,random-div必须绝对定位并且oCell相对定位。 The oCell div is positioned relative as it is within a table. oCell div在表中相对放置。

My problem is I need to find the absolute position of the oCell div, rather than the relative position. 我的问题是我需要找到oCell div的绝对位置,而不是相对位置。

So far I have: 到目前为止,我有:

var oCell = document.createElement("td");
var height = oCell.getBoundingClientRect().top;
var right = oCell.getBoundingClientRect().right;
oCell.oBoxPositionTop = height;
oCell.oBoxPositionSide = right; 

But from what I can understand, this is returning the relative height of oCell div, which is in turn not positioning random-div in the correct place. 但是据我所知,这是返回oCell div的相对高度,而这又没有将random-div定位在正确的位置。

The getBoundingClientRect gives coordinates in viewport coordinates (or coordinates relative to the visible content shown in your browser window). getBoundingClientRect以视口坐标(或相对于浏览器窗口中显示的可见内容的坐标)给出坐标。 With absolute positioning, you need document coordinates. 绝对定位时,您需要文档坐标。 To convert viewport coordinates to document coordinates, add the scroll offsets of the page to the left and top values returned by getBoundingClientRect: 要将视口坐标转换为文档坐标,请将页面的滚动偏移量添加到getBoundingClientRect返回的左侧和顶部值:

//technique used in JavaScript: Definitive Guide
var scrollOffsets = (function () {
    var w = window;

    // This works for all browsers except IE versions 8 and before
    if (w.pageXOffset != null) return {x: w.pageXOffset, y:w.pageYOffset};
    // For IE (or any browser) in Standards mode
    var d = w.document;
    if (document.compatMode == "CSS1Compat")
    return {x:d.documentElement.scrollLeft, y:d.documentElement.scrollTop};
    // For browsers in Quirks mode
    return { x: d.body.scrollLeft, y: d.body.scrollTop };
}());

//Your code:
var oCell = document.createElement("td");
//changed from height to top and gets document coordinates of position
var top = oCell.getBoundingClientRect().top + scrollOffsets.y;
//changed from right to left
var left = oCell.getBoundingClientRect().left + scrollOffsets.x;
oCell.oBoxPositionTop = top;
oCell.oBoxPositionSide = left;

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

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