JS: find width of all the images and sum them then apply this sum to the <p> element
I have a <p>aragraph which contains several images. The quantity of these images is not fixed, they're dynamically added via CMS. All the images have the same height but different width. I need to provide width="...px" to this
to use it with jScrollPane. I can NOT add "width" parameter to the img tag. What I need is to calculate width for eachimages inside this
, summarize and then use this sum as a <p> width.
<p id="photo" style="width: 3000px">
<img src="http://www.domain.com/images/image01.jpg" />
<img src="http://www.domain.com/images/image02.jpg" />
<img src="http://www.domain.com/images/image03.jpg" />
</p>
So I neeed to calculate width for image01.jpg, image02.jpg and image03.jpg and then apply the sum of these widths to the style="width: px".
I would appreciate any help with this matter. Than开发者_StackOverflow社区ks a lot!
Once your document is loaded, you can determine the width with the width or offsetWidth properties for each image and resize your paragraph according to the result.
If you don't want your images displayed until it's calculated I think it would work to give to your paragraph the style visibility:hidden until it's resized.
However, and depending on what you're trying to achieve, I would advise you to use the style white-space:nowrap to your paragraph instead of giving it a specific width.
Something like this?
var P = document.getElementById('photo');
var Imgs = P.getElementsByTagName('img');
var w = 0;
for ( var i = 0; i < Imgs.length; i++ ){
w += parseInt(Imgs[i].offsetWidth);
}
/* Here, w is your total width */
精彩评论