【问题标题】:JQuery variable in function strange behavior函数奇怪行为中的JQuery变量
【发布时间】:2015-11-05 02:11:23
【问题描述】:

我正在编写调整图像大小以适应容器大小的脚本。我写下了以下代码:

$(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 变量不应该在每个循环的每个函数调用中获取新值吗?

编辑:请注意所有容器的大小相同。

【问题讨论】:

  • 是的,它会得到更新。但如果该特定代码在页面加载之前运行,则不会。
  • 它应该可以工作,你能在演示中创建问题吗.. 唯一的问题是你可能需要等待图像加载
  • 上面的脚本在$(window).load()事件上可以正常工作。到那时所有图像都已加载。因此父 div 得到它的宽度。我认为问题在于事件而不是变量。

标签: jquery loops variables each behavior


【解决方案1】:

试试这个,

$(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%;
}

【讨论】:

    猜你喜欢
    • 2014-05-24
    • 1970-01-01
    • 2011-12-05
    • 2013-10-14
    • 1970-01-01
    • 2021-10-27
    • 2014-06-05
    • 2017-08-06
    • 1970-01-01
    相关资源
    最近更新 更多