javascript - 为所有图像添加宽度和高度属性

标签 javascript jquery

我需要通过 javascript/jquery 将 widthheight 属性添加到页面上的所有图像。这是由于我们的系统使用的工具造成的。我认为一个简单的每个循环,添加高度/宽度属性就足够了。不幸的是,这似乎不起作用

演示 https://jsfiddle.net/z86xnqd7/

$('body').find('img').each(function (index) {
    var theWidth = index.width();
    var theHeight = index.height();

    index.attr({
        "width": theWidth,
        "height": theHeight
    });
});

当您检查元素时,您会发现没有添加宽度/高度属性

最佳答案

jsFiddle:https://jsfiddle.net/CanvasCode/z86xnqd7/6/

您需要在加载事件中执行每个操作,您需要在检查图像的高度和宽度之前确保图像已加载。您还想使用 $(this) 而不是索引。

$(function () {
    $('img').load(function () {
        var theWidth = $(this).width();
        var theHeight = $(this).height();

        $(this).attr({
            "width": theWidth,
                "height": theHeight
        });

    });
});

关于javascript - 为所有图像添加宽度和高度属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32967527/

相关文章:

Javascript/Jquery 解析 Json 请求

javascript - Ramda,数组相等而不考虑顺序

javascript - 使用 beforeShow() 在日期选择器中添加类

javascript - meteorjs - 像 django 这样的管理员用户

javascript - 如何让确认框与 jsp 一起使用?

javascript - 在 jsp 中的 jquery 即时过滤器后,Html 选择不更改单击选项

javascript - 使用 jQuery 显示/隐藏复选框

javascript - 多次触发点击事件

javascript - EaselJS removeChild 是否也删除附加的 eventListeners?

javascript - 使用appendchild和html表的乘法表