我试图通过在 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 次没有居中。知道为什么吗?
最佳答案
如果你没有得到这个工作,我建议你使用 table-cell 方法使用 100% CSS 对齐。更少的 JavaScript 总是更好 :) 这是一个如何做到这一点的 jsfiddle
fiddle 中的代码:
<div>
<img src="http://explodingdog.com/drawing/awesome.jpg" />
</div>
div {
border: 1px solid red;
display:table-cell;
vertical-align: middle;
text-align: center;
height: 800px;
width: 800px;
}
img {
max-width:437px;
max-height:437px;
}
关于javascript - 刷新页面后图片位置不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16368922/