找到子图像宽度并将其应用于包含父div jquery [英] find child image width and apply it to containing parent div jquery

查看:151
本文介绍了找到子图像宽度并将其应用于包含父div jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个< img> 和一些< p> C>< DIV> 。



我想获得子img的宽度并将其应用到父div的宽度,以便文本的段落将换行宽度与img相同。

我希望能够在同一页面上多次迭代。



背景:
我正在开发一个使用jquery插件的wordPress主题( http ://desandro.com/resources/jquery-masonry )。我的主题与Gridalicious主题有一些共同之处( http://suprb.com/apps/gridalicious )但后宽和尺寸将由图像宽度决定,并不会是统一的。



我的html / css是一尘不染,但我的jquery / javascript很不稳定 - 但如果我能得到一些指示,我应该能够使用它。



任何帮助真正赞赏。

解决方案

这很好。请注意,您必须使用$(window).load()而不是$(document).ready(),因为$(document).ready()会在图像实际加载之前触发,因此图像将没有宽度。

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

编辑:请注意,这将以 div中的第一张图片。只需更改索引([0])以将其从另一个图像中取出即可。



编辑2:。 width()函数。


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.

解决方案

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.

这篇关于找到子图像宽度并将其应用于包含父div jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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