我不确定描述这一点的最佳方式。但是我找到了图像宽度,如果它小于 200px,它就会将 under-200 类应用于父 div。
$('.content').find('img').each(function () {
var $this = $(this), width = $this.width();
if (width < 200) {
$(this).parents('.container').addClass('under-200');
}
});
CSS: .container.under-200 {width: 200px}
这很好用,但我很难为较大的图像应用宽度。
因此对于 600px 的图像,jquery 将 600px 宽度应用于父 div,或者 434px 图像将 434px 宽度应用于父 div。
最佳答案
试试这个:
$(this).parents('.container').css("width", width);
此外,使用 .closest()
而不是 .parents()
。
.parents()
将通过 DOM 一直到根元素 HTML,然后根据您的选择器过滤结果。另一方面,.closest()
将在找到匹配项后立即停止。
您可以将所有代码归结为一行:
$(this).closest('.container').css("width", (width < 200 ? 200 : width ) );
希望这对您有所帮助!
关于jquery <比和>比.width,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9159634/