0
我试图在保持div内图像的正确纵横比并将其居中的同时对图像进行居中。我有以下的HTML代码:刷新页面后图像位置不正确
<div class="product-large" style="position: relative; overflow: hidden;">
<img src="/images/store_logos/c48edfde4dfb95efb42c5bb474fc249a2bc84253.jpeg" alt="" class="js-fix" style="margin-left: 0px; margin-top: 0px;">
<img src="/images/store_logos/c48edfde4dfb95efb42c5bb474fc249a2bc84253.jpeg" class="zoomImg" style="position: absolute; top: 0px; left: -3.3157894736842106px; opacity: 0; width: 500px; height: 760px; border: none; max-width: none;">
</div>
随着下面的JavaScript代码居中图像:
$(".product-large img").each(function() {
//get height and width (unitless) and divide by 2
var hWide = ($(this).width())/2; //half the image's width
var hTall = ($(this).height())/2; //half the image's height, etc.
// attach negative and pixel for CSS rule
hWide = '-' + hWide + 'px';
hTall = '-' + hTall + 'px';
$(this).addClass("js-fix").css({
"margin-left": hWide,
"margin-top": hTall
});
});
#main.product-detail .product-banner .product-large img
{
max-width:437px;
max-height:437px;
width:auto;
height:auto;
position:absolute;
top:50%;
left:50%;
}
#main.product-detail .product-banner .product-large {
background-color: #F3EFEA;
height: 437px;
width: 437px;
}
它适用于第一负载完全正常,但是第二次图像位置或破裂(即:它没有正确居中)。
对于一个工作示例,您可以检查链接below,然后刷新页面几次。你会注意到图像不是第2次/第3次居中。任何想法为什么?
事实上,我注意到,当我打开页面的第一时间,'.js-fix'的边际不在那里。但我可以问为什么你使用'javascript'来居中图像?为什么不在'.product-large'上使用'text-align:center'并从img中删除'position:absolute'? – LRA 2013-05-03 23:36:56
什么是'js-fix'类?我认为它没有被使用。 – cortex 2013-05-03 23:37:44
@LRA我正在尝试将图片居中,但我不想打破宽高比,所以我认为这会解决它 – adit 2013-05-03 23:39:29