find child image width and apply it to containing parent div jquery

我们两清 提交于 2019-12-11 09:48:03

问题


I have an <img> and some <p>'s inside a <div>.

I want to get the width of the child img and apply it to the width of the parent div so that the paragraphs of text will wrap to the same width as the img.

I want to be able to do this to multiple iterations on the same page.

Background: I am developing a wordPress theme that uses the masonry jquery plugin (http://desandro.com/resources/jquery-masonry). My theme has something in common with Gridalicious theme (http://suprb.com/apps/gridalicious) but the post widths and sizes will be dictated by the image width and will not be uniform.

My html/css is spotless but my jquery / javascript is pretty shaky - but if I can get some pointers I should be able to work with it.

Any help truly appreciated.


回答1:


This works perfectly. Note that you have to use $(window).load() instead of $(document).ready(), because $(document).ready() fires before images are actually loaded, and thus the images will have no width.

$(window).load(function() {
    $('div').each(function() {
        $(this).width($(this).find('img').width());
    });
});

Edit: Note that this will base the width off of the first image in the div. Simply change the index ([0]) to base it off another image in the div.

Edit 2: Applied John's correction on the .width() function.




回答2:


This will find all the divs on the page and set their widths equal to their img child element's width.

 $('.divselector').attr('width', $(this).find('img').attr('width'))



回答3:


You don't need to use Javascript at all for this. If you put the image and the p into child divs, this can be done purely in CSS as in Chris's solution (here's the JSFiddle: http://jsfiddle.net/glee/qs8GJ/ to the following SO question: css - shrink a parent div to fit one child's width and constrain the width of the other child

The trick is to set the parent div to...

display: table-cell;

the image div to...

display: table-row;
width: 1px;

...and the div containing the paragraph text to

display: table-cell;
width: 1px;

Works like charm!



来源:https://stackoverflow.com/questions/3194962/find-child-image-width-and-apply-it-to-containing-parent-div-jquery

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