我正在编写调整图像大小以适应容器大小的脚本。我写下了以下代码:
$(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%;
}
关于函数中的 JQuery 变量有奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31965701/