【问题标题】:calculating width & height relative to container using jquery使用jquery计算相对于容器的宽度和高度
【发布时间】:2012-12-28 13:45:54
【问题描述】:

我的图像容器是 image-wrap 类,.image-wrap img 宽度和高度设置为 100% 填充容器。

CSS:

    .image-wrap{
    width:600px;
    height:400px;
    position:relative;
    overflow:hidden;
    }
    .image-wrap img{
    position:relative;
    width:100%;
    height:100%;
    }

现在我想在 image-warp 中设置 5 px 的填充,这还需要将 .image-wrap img 的宽度和高度更改为另一个 % 值。如何计算并将其设置为 jquery var,因此我可以使用 jquery 将其添加到 image-wrap img 类。即使对于image-wrap 的任何其他宽度-高度值对(可能用于响应式设计),我的 5 px 填充保持不变。帮助我评估数学方程以将宽度高度 % 设置为 jquery var。

【问题讨论】:

  • 如果您想保留图片的百分比,则公式为 590*100/600。然后是 99.something %。
  • 我想设置 5 px 的内边距。所以我的图像宽度和高度总是比图像包装容器的高度宽度小 10 px。
  • 谢谢斯文!你已经这样计算了(600px-10px)。但我想用jquery为容器的任何高度-宽度参数计算它。
  • 那么您在公式中不使用固定数字,您只需查询元素的高度/宽度并从中减去 10px。然后你动态地拥有它。

标签: jquery css variables jquery-selectors


【解决方案1】:
jQuery(".image-wrap").each(function() {

    myWidth = jQuery(this).width();
    myHeight = jQuery(this).height();
    myWidth = myWidth - 10;
    myHeight = myHeight - 10;
    myWidth = myWidth.toString().concat("px");
    myHeight = myHeight.toString().concat("px");

    jQuery(this).find("img").css({

        height: myHeight,
        width: myWidth
    });
});

希望对你有帮助

【讨论】:

  • 我已经得到了相同的。不需要 concat("px)。我们可以简单地通过 var + "px" 得到它。
【解决方案2】:

jQuery:

   var $imgHeight = $('.image-wrap img').height();
   var $imgWidth = $('.image-wrap img').width();

你也可以用 css3 做到这一点:

.image-wrap img{
  position:relative;
  width: calc(100% - 10px);
  height: calc(100% - 10px);
  padding: 5px;
}

【讨论】:

  • 这不是真的,你可以用 jquery 做到这一点,没有任何仅部分支持的 CSS3 属性。
  • 这只是一个例子,它只能用 css 来完成。它有什么问题?
  • 你写你只能用 CSS3 是错误的。这给人的印象是没有其他可能性。
【解决方案3】:
jQuery("img.image-wrap").css({padding:'5px', width:'590px', height:'390px'});

希望对你有帮助

【讨论】:

  • 感谢您的回答!这是用 height 固定的,但我想为任何高度宽度对动态设置它。
猜你喜欢
  • 2018-01-16
  • 2014-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-01
  • 1970-01-01
  • 2013-02-14
相关资源
最近更新 更多