我是jQuery的新手,遇到了一个问题。
我有一个脚本,可以调整某个div中每个图像的大小。我想将该图像插入不存在的div(创建div-parent),怎么办?
编辑:
我有以下代码:
$('#content img').each(function() {
if( $(this).width() > maxWidth || $(this).height() > maxHeight )
{
var ratio = 0;
if( $(this).width() > $(this).height() )
{
ratio = maxWidth / $(this).width();
$(this).css('width', maxWidth + 'px');
$(this).css('height', ( $(this).height() * ratio) + 'px' );
}
else
{
ratio = maxHeight / $(this).height();
$(this).css('width', ($(this).width() * ratio) + 'px');
$(this).css('height', maxHeight + 'px');
}
$(this).addClass('scaled-img');
$(this).wrap('<div class="test"></div>'); // trying to add
}
});
});
结果:
<img src="path.."/>
Result that i want:
<div><img src="path"/></div>
$(this)
。那是非常低效的代码。获取对$(this)
返回值的单个引用,并将其保存为局部变量,以便您可以重复使用它:var $this = $(this); ... if ($this.width() ...) ...
同样,保存计算出的宽度和高度,没有理由继续计算它们。 - Matt Ball