根据容器 DIV 中的图像动态调整容器 DIV 的大小

Dynamically resizing a container DIV based on the image inside of it

本文关键字:DIV 调整 整容 动态 图像      更新时间:2023-09-26

我正在使用可调整大小的函数来操作一些图像,我想知道是否可以有一个容器 DIV(特别是.下面的容器)围绕图像以动态调整大小以及其中的图像。请参阅此JSFIDDLE以获取有关我要查找的示例。

.HTML

<div class="container">
  <div class="resizable" class="ui-state-active">
      <img src="http://41.media.tumblr.com/3e99c08237117645f55cd1c4bdbf3180/tumblr_mky50dQmXI1s56exfo1_500.png" alt="doge">
  </div>
</div>

.CSS

.container { width: auto; height: auto; }
.resizable { background-position: top left; width: 150px; height: 200px; }
    .resizable, .container { padding: 0.5em; }
        .resizable img {width:100%;}

.JS

$(function() {
    $( ".resizable" ).resizable({
      containment: ".container",
      aspectRatio: 150/200
    });
});

最初,我认为也许将容器的宽度/高度放置在 AUTO 可以解决这个问题,但是,只有 DIV 长度的 100%。

思潮?

进行此更改,它将起作用。将容器宽度和高度设置为自动,并显示内联块,以便不采用完整的父宽度。

.CSS

.container { width: auto; height: auto; display: inline-block; }
.resizable { background-position: top left; width: 150px; height: 200px; }
    .resizable, .container { padding: 0.5em; }
        .resizable img {width:100%;}

此外,您还必须删除js的包含行。

.JS

$(function() {
    $( ".resizable" ).resizable({
        aspectRatio: 150/200
    });
});