我在运行时使用javascript创建了一个div(oCell)。
然后,我想相对于该div定位另一个独立的div(随机div)。由于程序内的原因,random-div必须绝对定位,而oCell相对定位。oCell div在表中相对放置。
我的问题是我需要找到oCell div的绝对位置,而不是相对位置。
到目前为止,我有:
var oCell = document.createElement("td");
var height = oCell.getBoundingClientRect().top;
var right = oCell.getBoundingClientRect().right;
oCell.oBoxPositionTop = height;
oCell.oBoxPositionSide = right;
但是据我所知,这是返回oCell div的相对高度,而这又没有将random-div定位在正确的位置。
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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句