2012-05-11 121 views
1

我有一个元素包含两个图像,一个层叠在另一个之上。包含元素左侧浮动并排成三列。我已经使用了jQuery修补程序将图像集中到其元素中。我不得不使用jQuery,因为它是一个响应式设计,因此图像更改大小。除了某些移动设备之外,这一切都很有效。在按下随机元素之前,图像宽度似乎没有被计算出来?我希望这是有道理的。该网址是mooble.co.uk及其左侧较大的图片。居中绝对定位元素

**编辑

对不起,我没有说清楚,我已经使用该解决方案工作正常,但在移动设备上的宽度和左边距似乎并没有被负载计算?大概20秒后,它似乎就会弹出位置。

编辑**

<div class="g1" id="mass"> 
<p><span class="highlight"></span></p> 
<div id="mass-cont"> 

<img class="bottom" src="images/mass.png" /> 
<img class="top" src="images/no-mass.png" /> 


</div> 

</div> 

CSS

#mass{position:relative;} 
#mass-cont{} 
#mass img{position:absolute;left:50%;} 
#mass img{transition: opacity 1s ease-in-out;display:block;} 
#mass img.top:hover{opacity:0;} 

JS

//Functions 
function setImageHeight(){ 

var imageSize = $('.bottom').height(); 
$('#mass-cont').height(imageSize); 

var imageWidth = $('.bottom').width(); 
var position = imageWidth/2; 

$('#mass-cont > img').css('margin-left' , '-'+ position + 'px'); 

} 

//Load Document 
$(document).ready(function() { 

//Set image height 

$('.bottom').load(function(){ 

setImageHeight(); 

}); 

$(window).resize(function() { 

setImageHeight(); 


}); 

}); 
+0

试试这个:1)http://www.zachgraeve.com/2006/10/01/center-abosulte-position-div/ 2)http://www.sitepoint.com/css-center -position-absolute-div/ –

回答

1

我甲肝e基于过去的窗口宽度完成它并设置元素的左边距。

$(window).resize(function() { 
setPosition(); 
}); 

$(document).ready(function() { 
setPosition(); 
}); 

function setPosition(){ 
var WindowWidth = $(window).width(); 
var BottomWidth = 300; //The width of bottom 
Left Position = (WindowWidth - BottomWidth)/2; 
$(".bottom").css("margin-left", BottomWidth + "px"); 
} 
+0

嗨,感谢您的回复。我使用的解决方案与您的解决方案的工作方式相同,但移动设备似乎无法计算负载上的所有内容? – jhodgson4

+0

哦,我看到的移动宽度,我认为你必须使用这样的东西。 http://css-tricks.com/css-media-queries/ – Paul

0

试试这个:

left = ($("#mass-cont").width() - $(".bottom").width())/2; 
$(".bottom").css("left", left)