【问题标题】:Jquery have a parent div have the same width and height of it's child elementJquery 有一个父 div 有相同的宽度和它的子元素的高度
【发布时间】:2013-09-15 19:36:02
【问题描述】:

我要解决这个问题已经好几个星期了,我真的需要帮助。

我有这个系统,其中用户选择具有 2 种区域类型的模板。一种用于插入图像,一种用于插入文本。
每个模板可能带有许多区域来插入图像,每个图像区域只是一个 div,在 800px - 650px 的有限区域内具有自己的尺寸 [width px - height px]。

我会调用这个div来接收图片div.img

div.img 里面有一个 input type="file" 并抛出 jquery.form.js 插件,我可以在其中插入一个新图像。

我会调用插入的图片new.img

这个new.img 包含在一个 div div.newImg 中,因为我必须有一个按钮来删除图像本身顶部的图像。

我正在使用 jquery ui 可拖动和调整大小,因此 div.newImg 可以调整大小并拖动到 div.img 内。

这里是不同的元素:div.img -> div.newImg -> new.img + 按钮删除

HTML

<div class="child" style="z-index: 70; position: absolute; top: 0px; left: 0px; width: 800px; height: 172px; cursor: default; background-color: rgba(254, 202, 64, 0.701961);" alt="reset">
   <div class="imgh ui-resizable ui-draggable" alt="reset3" style="height: 100%; width: 204px;">
      <img src="###" style="width:inherit; height:inherit;  min-width:50px; min-height:50px;" class="img_set">
      <div class="close"><i class="icon-remove-sign"></i></div>
   </div>
</div>

JQUERY

$('.imgh').resizable({ containment: $(this).closest('.child') });
$('.imgh').draggable({ containment: $(this).closest('.child'), scroll: true, snap: true, snapTolerance: 5 });

这是我迄今为止设法解决的问题,但对我一点帮助都没有

if($('.child').width() > $('.child').height()){
    $('.imgh').height('100%');
    $('.imgh').width($('.imgh img').width());
}else{
    $('.imgh').width('100%');
    $('.imgh').height($('.imgh img').height());
}

通过拥有style="width:inherit; height:inherit;",我设法让img.img_set 具有与其父级相同的尺寸。

我需要一种使div.imgh 与内部img.img_set 具有相同尺寸的方法。就像一个颠倒的inherit

更新
这段代码做了我想要的,但我的问题是每次我调整大小时都会回到我在初始化中定义的:

if($('.child').width() > $('.child').height()){
    $('.imgh').height('100%');
    $('.imgh').width('auto');
}else{
    $('.imgh').width('100%');
    $('.imgh').height('auto');
}
if($('.imgh').width() > $('.imgh img').width()){
    $('.imgh').width($('.imgh img').width());
}

有没有办法让每个div.imgh 只发生一次?

【问题讨论】:

  • 一个浮动或绝对定位的块元素,高度和宽度设置为auto 将自动扩展到其内容。那么,您也许可以完全使用 CSS 来实现这一点?
  • 我已经将其设置为自动,它在 div.child 内将宽度扩大了 100%,我似乎找不到原因
  • 你是浮动还是设置为position: absolutediv.imgh 可以定位 absolute 并且没有指定宽度。然后它将扩展到它的内容(子)。
  • 是的,我有.imgh{ position: absolute; top:0; cursor: move; overflow: hidden;},即使我没有设置宽度,它也会扩大100%
  • What I need is a way for the div.imgh to have the same dimensions as it's inner img.img_set。这不是在这个小提琴中完成的吗(我在.imgh 中添加了红色背景,以便您更好地查看它的尺寸。

标签: javascript jquery html css image


【解决方案1】:

您可以使用 .bind() 来调整它的大小,每次发生变化...

$('.imgh').bind('resize', FullWidthHeight); //Note: check the 'resize' event is relevant to imgh

function FullWidthHeight() {
    $('.imgh').css('height', img.img_set.height());
    $('.imgh').css('width', img.img_set.width());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 2014-12-10
    • 2016-03-02
    • 2021-02-09
    • 1970-01-01
    • 2015-09-21
    • 2013-09-16
    相关资源
    最近更新 更多