我有一个自定义控件,需要将弹出窗口直接呈现在其“主”控件主体( DIV元素)下面。我遇到的问题是,如果控件不了解其容器设置,如何设置弹出坐标位置。
例如,以这一节代码为例:
// library call to extract document-based coordinates (returns object with X and Y fields) of the "controlBodyElement" (a DIV)
var pt = some.library.getDocumentPosition(controlBodyElement)
// frame (the "popup") is a DIV pointer
frame.style.position = "absolute"
frame.style.top = pt.y + controlBodyElement.clientHeight + 1 + "px" // Line "A"
// frame.style.top = "0px" // Line "B" -- finds the relativity point of absolute-position 行"A“-导致弹出窗口呈现在controlBodyElement下方
行"B“-呈现弹出的方式以上的controlBodyElement。
问:应该在DOM树中搜索哪些元素设置/属性,以确定某个绝对定位的子元素相对于哪个元素锚定?
更新:我想如果有人能向我解释什么页面机制会导致一个绝对定位的元素(使用top = 0px)被呈现在页面的一半(而不是顶部),那么我就可以写出逻辑来解决问题;我只是不确定我是否需要寻找.
发布于 2013-09-12 04:54:57
感谢Pumbaa80提供的信息--这正是我想弄清楚的。
为了以后帮助其他人,下面是一个改进的定位器方法,它将提取特定的偏移坐标(相对于逻辑屏幕位置).
// relative location from nearest Positioned ancestor
getPositionedOffset = function(element, coordinates) {
// create a coordinates object if one was not assigned (first iteration)
if(coordinates == undefined) {
coordinates = {x: 0, y: 0 }
}
if (element.offsetParent) {
switch(window.getComputedStyle(element).position) {
case "relative":
case "absolute":
case "fixed":
return coordinates
default:
coordinates.x += element.offsetLeft
coordinates.y += element.offsetTop
getPositionedOffset(element.offsetParent, coordinates) // step into offsetParent
}
}
return coordinates
}注意:代码在Chrome中是有功能的;在其他浏览器版本中操作时需要做一些小的调整。
编辑:
在大多数情况下,函数将使用单个参数(作为元素引用)调用,如下所示:
var ele = document.getElementById("foo")
var relativeLoc = getPositionedOffset(ele)但是,如果需要考虑手动移位(例如,+5 5px右,和-10 5px up),则包括第二个参数:
var relativeLocWithOffset = getPositionedOffset(ele, {x:5, y:-10}) https://stackoverflow.com/questions/18754631
复制相似问题