我正在使用两种JavaScript方法来定位页面上静态元素内的悬停按钮。居中的按钮被输入到第一个元素中,并使用绝对定位。我使用以下代码获取父元素的尺寸:
现在我的问题是,第三方库需要将父级DIV的位置从浏览器默认的“静态”更改为“相对”,这会破坏我在第二个函数中的计算。也许已经晚了,但无论我尝试什么,似乎都无法弄清楚如何在父元素的位置设置为相对时使其工作。我似乎无法正确处理数学问题,我的头开始疼了。有什么建议吗?编辑-添加JSFIDDLE。
// calculate if the element is in the visible window
function elementVisibleRect(element) {
element = $(element);
var rect = {
top: Math.round(element.offset().top),
left: Math.round(element.offset().left),
width: Math.round(element.outerWidth()),
height: Math.round(element.outerHeight())
};
var scrollTop = $(window).scrollTop();
var windowHeight = $(window).height();
var scrollBottom = scrollTop + windowHeight;
var elementBottom = Math.round(rect.height + rect.top);
if (scrollTop < rect.top && scrollBottom > elementBottom) {
return rect;
}
if (scrollTop > rect.top) {
rect.top = scrollTop;
}
if (scrollBottom < elementBottom) {
rect.height = scrollBottom - rect.top;
} else {
rect.height = windowHeight - (scrollBottom - elementBottom);
}
return rect;
}
为了使用这些信息并将按钮居中
// center the element based on visible screen-frame
function elementPosition (element) {
var visibleRect = elementVisibleRect(element);
$('.editHoverButton').css({
top: visibleRect.top + ((visibleRect.height / 2) - ($('.editHoverButton').outerHeight() / 2)),
left: visibleRect.left + (visibleRect.width / 2) - ($('.editHoverButton').outerWidth() / 2)
});
}
现在我的问题是,第三方库需要将父级DIV的位置从浏览器默认的“静态”更改为“相对”,这会破坏我在第二个函数中的计算。也许已经晚了,但无论我尝试什么,似乎都无法弄清楚如何在父元素的位置设置为相对时使其工作。我似乎无法正确处理数学问题,我的头开始疼了。有什么建议吗?编辑-添加JSFIDDLE。