我正在研究调整图像大小以适合容器大小的脚本。我写下了以下代码:
$(function () {
$('.postbody .content img').each(function () {
var containerWidth = $(this).parent().width();
if ($(this).width() > containerWidth) {
$(this).width(containerWidth);
$(this).wrap('<a href="' + $(this).attr('src') + '" target="_blank"></a>');
}
});
});
但这仅适用于循环中的第一个元素。根据我以前在将jQuery方法分配给变量之后遇到的问题,我对代码进行了一些更改:
$(function (){
$('.postbody .content img').each(function () {
if ($(this).width() > $(this).parent().width()) {
$(this).width( $(this).parent().width() );
$(this).wrap('<a href="'+$(this).attr('src')+'" target="_blank"></a>');
}
});
});
现在,它可以完美运行。但是我不知道怎么做。
containerWidth
变量是否不应该通过每个循环的每个函数调用获取新值?编辑:请注意,所有容器的大小均相等。
最佳答案
尝试这个,
$(function () {
$('.postbody .content').each(function () {
var containerWidth = $(this).width();
var img = $(this).find("img");
if (img.width() > containerWidth) {
img.width(containerWidth);
img.wrap('<a href="' + img.attr('src') + '" target="_blank"></a>');
}
});
});
或者您可以仅使用CSS执行相同的操作
只需将img标签的最大宽度设置为100%
例如
img {
max-width: 100%;
}