Calculate the width and height of parent div and apply to image accordingly

微笑、不失礼 提交于 2019-12-07 19:57:13

问题


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>

the generated code which I need would be

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

Thank you in anticipation


回答1:


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

The differences are:

  • 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

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

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


来源:https://stackoverflow.com/questions/11677222/calculate-the-width-and-height-of-parent-div-and-apply-to-image-accordingly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!