我想让图像在加载后旋转并填充容器。我遇到的问题是高度在加载时自动设置,然后在旋转后不重置。这是该问题的 JSFiddle:
$('.load').on("click", function () {
var image = $('.image');
image.attr("src", "https://s-media-cache-ak0.pinimg.com/736x/f5/a0/62/f5a0626a80fe6026c0ac65cdc2d8ede2.jpg");
image.addClass('rotate-image');
});
.image {
max-width: 100%;
max-height: 100%;
}
.rotate-image {
transform: rotate(90deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="img-container" style="background:black; height:100px; width: 200px; text-align:center">
<img class="image" src="" />
</div>
<br />
<button class="load">Load</button>
最佳答案
但这需要删除 max-width
和 max-height
样式。
为了适应图像,必须将其放大,使其宽度(旋转时的高度)变得与容器的高度一样大。但是,它仅在视觉上进行旋转,浏览器并不关心这一点,因为 transform
不会改变网站的流程。对于它,有一个“未旋转”的图片,其高度现在大于其容器。视觉上旋转图像不会改变任何东西。为此,需要将图像拉出,其像素数等于其比父级大的像素数。这些像素被除以二,因为图像仅在底部溢出。
玩fiddle明白我的意思。
$('.load').on("click", function() {
var image = $('.image');
image.attr("src", "https://s-media-cache-ak0.pinimg.com/736x/f5/a0/62/f5a0626a80fe6026c0ac65cdc2d8ede2.jpg");
image.addClass('rotate-image');
var parentHeight = image.parent().height();
image.css("width", parentHeight + "px");
image.css("position", "relative");
image.css("bottom", ((image.height() - parentHeight) / 2) + "px");
});
.rotate-image {
transform: rotate(90deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="img-container" style="background:black; height:100px; width: 200px; text-align:center">
<img class="image" src="" />
</div>
<br />
<button class="load">Load</button>
编辑:请注意,如果您通过设置 src
从外部源加载图像并立即旋转它,image.height()
可能会返回 0 并且图像可能会移位。然后,如果您再次单击,它的高度现在是正确的并且放置在正确的位置。
我不太确定,但我认为这是因为当您加载图像时,浏览器需要先下载它,这意味着您还不知道它的尺寸是多少。
要查看实际效果,请将来自 Google 的一些图像网址粘贴到我提供的 fiddle 中。
关于javascript - 让图像在变换后填充容器(90deg),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42462347/