[英]jQuery .offset() not retrieving correct position
我正在开发一个通过PHP动态创建类似facebook的按钮的网站。 但是,包含按钮的<div>
需要具有CSS属性overflow: hidden;
这是我发现的唯一方法,它可以制作一个双列格式,强制两列扩展为最长列的长度。 这种方法的唯一问题是,当有人点击它们并扩展时,放置在容器底部附近的任何类似facebook的按钮都会被剪裁。
这是我试图解决这个问题的方式:
使用jQuery,我遍历页面上的所有类似facebook的按钮,并使用offset()
方法计算其文档偏移offset()
。
然后我clone()
每个按钮,并使用jQuery的css()
方法给它绝对定位和计算的偏移量。 我希望每个克隆按钮都放在与我将其附加到文档时克隆的按钮的相同位置。
最后,我将每个旧的类Facebook按钮的css更改为visibility: hidden;
为了使它不可见但仍占用它以前在页面上的空间。 我将类似facebook的按钮的克隆添加到div而没有overflow: hidden;
使用appendTo()
函数的属性。
这是我完成此过程的完整代码:
// Replaces functional facebook recommend buttons with identical ones
// in a div where they won't get clipped when they expand.
// Hides the old buttons so space is still left for new ones
$(window).load(function(){
$(".fb-recommend").each(function(){ // cycle through each recommend button
var offset = $(this).offset(); // calculate offset of each button
var newButton = $(this).clone(); // clone the button
newButton.css({'position':'absolute', 'left':offset.left, 'top':offset.top});
$(this).css("visibility","hidden"); // hide the old button
newButton.appendTo("#wrapper"); // put the new button in the wrapper where it won't get clipped
});
});
在所有这些结束时,我希望每个按钮的克隆放在旧按钮的位置,但是在另一个<div>
。 整个过程是有效的,除了克隆的类似于facebook的按钮出现在与它们克隆的位置略有不同的位置(如PitaJ指出它们似乎偏离了大约39px的垂直偏移倍数)。 您可以在此处查看问题:
如您所见,第一个按钮放置在正确的位置(由隐藏的克隆填充的空白空间),但其他偏移未正确计算。
我很感激任何想法或帮助。 如果您希望我更好地解释或发布更多代码,请告诉我们!
编辑:我想我会在这里发布类似于facebook的按钮的CSS(即使我正在改变的是边距):
#content .fb-recommend {
margin: 15px 0 5px 0;
}
编辑2:根据UnLoco的建议,我在fb-reccommend CSS中添加了一个min-height属性,并注释掉了隐藏旧按钮的代码行,因此更容易看到问题(虽然稍有减少但仍然存在) CSS现在看起来像这样:
#content .fb-recommend {
margin: 15px 0 5px 0;
min-height: 39px;
}
编辑3:问题似乎已在所有浏览器中解决,但IE通过将CSS更改为:
.fb-recommend {
min-height: 24px; // I used 24 because the fb-buttons are 24px in height
}
最终编辑? 这似乎适用于我的所有浏览器,包括IE:
.fb-recommend {
min-height: 39px;
}
我现在想的是,39可能来自旧fb按钮的15px边距+ 24px高度。 我想我可以通过简单地将高度设置为39px并且没有边距来绕过它。
这是因为您在fb iframe实际加载之前检索偏移量。 只需添加这样的css规则
div.fb-recommend{min-height:39px}
我相信你的问题是一些奇怪的jQuery怪异。
要解决此问题,只需将代码更改为:
$(window).load(function(){
$(".fb-recommend").each(function(index){ // cycle through each recommend button
var offset = $(this).offset(); // calculate offset of each button
var newButton = $(this).clone(); // clone the button
newButton.css({'position':'absolute', 'left':offset.left, 'top':offset.top + (39*index)});
$(this).css("visibility","hidden"); // hide the old button
newButton.appendTo("#wrapper"); // put the new button in the wrapper where it won't get clipped
});
});
这将解释奇怪的偏移问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.