Jquery 计算父div的宽度和高度,并相应地应用于图像

Jquery 计算父div的宽度和高度,并相应地应用于图像,jquery,scale,Jquery,Scale,我有一个父div,它具有响应宽度和固定高度,其中包含一些图像。在运行时,我需要一个Jquery函数来计算div的宽度和高度,并将宽度(px)和高度(px)参数应用于图像。i、 我现在的代码是 <div id="slider-wrapper" class="someclass"> <img src="/image1.jpg" alt="" /> <img src="/image2.jpg" alt="" /> <img src="/

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

<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()

区别在于:

  • height()
  • innerHeight()
    返回元素高度和填充
  • outerHeight()
    返回元素高度、填充和边框
  • outerHeight(true)
    返回元素高度、填充、边框和边距
在这篇文章中,我有更多的细节,包括使用JSFIDLE的输出示例

对于宽度,可以使用
width()
innerWidth()
outerWidth()

同样的逻辑适用于高度

所有值均以像素为单位

要获得高度/宽度,您可以使用与以下类似的方法:

// 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();
要设置高度/宽度,可以使用与以下类似的方法:

// 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);

为什么你的金徽章少了完美;)@用户1305063:谢谢。我很高兴这有帮助。