jQuery和margin:0 auto [英] jQuery and margin: 0 auto
问题描述
所以,这是一个问题,以前被问过,但我希望我们可以搁置休息:我使用jQuery 1.4。如果我定义样式
So, this is a problem that's been asked before, but I'm hoping we can lay it to rest: I'm using jQuery 1.4. If I define the style
#obj { margin: 0 auto; }
然后执行
$('#obj').css('marginLeft');
结果是以像素计算的值。是否有任何方法来判断这些像素是否来自 auto
计算,而不解析 document.styleSheets
?
the result is the computed value in pixels. Is there any way to tell whether those pixels come from the auto
calculation or not, without parsing document.styleSheets
?
推荐答案
如果边距设置为百分比,也会触发此解决方案,但它可能足以满足您的需求。基本上,你记录调整大小时改变哪些边距。因此,您需要在将数据大小调整为数组之前记录边距:
This solution would also be triggered if the margins were set to percentages, but it might be good enough for your purposes. Basically, you record which margins change on resize. So you'd record the margins before resize to an array:
var aMargins = [];
$('.yourObjs').each(function(i,obj){
var objML = $(obj).css('marginLeft');
aMargins.push(objML);
});
然后重新调整窗口大小,查看更改了哪些页边距(这些将是auto做你需要做的和他们的窗口回到原始大小:
Then resize the window, see which margins changed (these will be either 'auto' or %), do what you need to do to them and return he window to original size:
var wW = $(window).width();
var wH = $(window).height();
window.resizeTo(wW - 5, wH);
$('.yourObjs').each(function(i,obj){
if ($(obj).css('marginLeft') != aMargins[i]) {
// your centering code here
}
}
window.resizeTo(wW,wH);
如果你的中心代码只是调整左边距,那么这应该适用于基于%的边距。我不能测试这个代码或提供一个例子,因为我在路上,写我的电话,但希望这可以工作或帮助你想出的东西。
If your centering code just adjusts the left margin then this should work fine for % based margins too. I can't test this code or provide an example because I'm on the road and writing from my phone, but hopefully this works or helps you come up with something that will.
这篇关于jQuery和margin:0 auto的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!