注意:我重写了我的答案,因为我之前的解决方案在 Firefox 中不起作用(哦,具有讽刺意味)。它还在其他浏览器中引起了奇怪的行为。原因是 flexbox 将图像垂直和水平居中。
让我们一步一步来。
为了在设置最大尺寸的同时保持图像的纵横比,可以通过以下方式实现:
.img {
display: block; // could also be inline-block or other block-like types
max-height: 100%;
max-width: 100%;
height: auto;
width: auto;
}
现在,从技术上讲,使用 flexbox 使元素垂直和水平居中只需 3 行代码。如上所述,这在某些浏览器中缩放图像时会导致奇怪的行为。相反,我们使用text-align: center 将图像沿 x 轴居中,并使用一种称为“幽灵元素”的方法将图像沿 y 轴居中。您可以在this article from CSS Tricks 中了解更多信息。总之,我们有这个使元素居中:
.parent {
text-align: center;
white-space: nowrap;
}
.parent:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em;
}
.centered-child {
display: inline-block;
vertical-align: middle;
}
最后,我们结合了缩放和居中。我假设 HTML 在正文中仅存在一个 <img class="img" ...>。
html {
width: 100%;
height: 100%;
}
body {
margin: 0;
width: 100%;
height: 100%;
background-color: #333;
text-align: center;
}
body:before {
content: '';
width: 0;
height: 100%;
display: inline-block;
vertical-align: middle;
white-space: nowrap;
margin-left: -0.25em;
}
.img {
display: inline-block;
vertical-align: middle;
max-height: 100%;
max-width: 100%;
width: auto;
height: auto;
}
现在我们实现缩放
为了缩放图像,我们需要 JavaScript。让我们使用 jQuery。
在 JavaScript 中更改 css 属性不好,所以我们准备了两个额外的类。
.img.is-zoomable {
cursor: zoom-in;
}
.img.is-zoomed {
cursor: zoom-out;
max-height: none;
max-width: none;
}
点击时,JavaScript 将切换 is-zoomed 类,而在 mouseenter 时,我们决定是否可以缩放图像。如果可以缩放,我们添加类is-zoomable。
$('.img').on('click', function() {
$(this).toggleClass('is-zoomed');
});
$('.img').on('mouseenter', function() {
var origWidth = this.naturalWidth;
var origHeight = this.naturalHeight;
var currWidth = $(this).width();
var currHeight = $(this).height();
if (origWidth !== currWidth || origHeight !== currHeight) {
$(this).addClass('is-zoomable');
}
});
等等,我们完成了。有关工作示例,请参阅my codepen。