计算父div的宽度和高度,并相应地应用于图像 [英] Calculate the width and height of parent div and apply to image accordingly

查看:46
本文介绍了计算父div的宽度和高度,并相应地应用于图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父div,该div的响应宽度和高度固定,其中包含一些图像.在运行时,我需要一个Jquery函数来计算div的宽度和高度,并将width(px)和height(px)参数应用于图像.即我的代码现在是

I have a parent div which in responsive width and fixed height with some images inside it. On runtime I need a Jquery function to calculate the width and height of the div and apply the width (px) and height (px) parameters to image. i.e my code right now is

<div id="slider-wrapper" class="someclass">
    <img src="/image1.jpg" alt="" />
    <img src="/image2.jpg" alt="" />
    <img src="/image3.jpg" alt="" />
</div>

我需要的生成代码是

  <div id="slider-wrapper" class="someclass">
    <img src="/image1.jpg" height="300px" width="total-div-width(px)" alt="" />
    <img src="/image2.jpg" height="300px" width="total-div-width(px)" alt="" />
    <img src="/image3.jpg" height="300px" width="total-div-width(px)" alt="" />
</div>

谢谢您的期待

推荐答案

使用jQuery,您可以使用.height().innerHeight().outerHeight().

Using jQuery you can use .height(), .innerHeight() or .outerHeight().

区别是:

  • height()仅返回元素的高度,没有边框,没有边距,也没有填充
  • innerHeight()返回元素高度和填充
  • outerHeight()返回元素的高度,填充和边框
  • outerHeight(true)返回元素的高度,填充,边框和边距
  • height() returns just the height of the element, no borders, no margins and no padding
  • innerHeight() returns the element height and the padding
  • outerHeight() returns the element height, the padding and borders
  • outerHeight(true) returns the element height, the padding, borders and margins

我在此帖子的此处中有更多详细信息,包括使用jsFiddle的输出示例.

I have more details including output examples using jsFiddle in this post here.

对于宽度,您可以使用width()innerWidth()outerWidth().
逻辑与高度相同.

For width you can use width(), innerWidth() or outerWidth().
The same logic applies as with height.

所有值均以像素为单位.

All values are in pixels.

要获取高度/宽度,您可以类似于以下方式使用它:

To get the height/width you can use it similar to this:

// The below is an example, you need to add your element references as required.

// Use height(), innerHeight() or outerHeight() as needed.
var newHeight = $("#slider-wrapper").height();

// Use width(), innerWidth() or outerWidth() as needed.
var newWidth = $("#slider-wrapper").width();

要设置高度/宽度,您可以类似于以下方式使用它:

To set the height/width you can use it similar to:

// The below is an example, you need to add your element references as required.
var newHeight = $("#slider-wrapper img").height(newHeight);
var newWidth = $("#slider-wrapper img").width(newWidth);

这篇关于计算父div的宽度和高度,并相应地应用于图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆