简体   繁体   English

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

[英]Add width and height attr to all images

I need width and height attributes added to all images on a page via javascript/jquery. 我需要通过javascript / jquery将widthheight属性添加到页面上的所有图像。 This is due to a tool our systems use. 这是由于我们的系统使用了一种工具。 I thought a simple each loop, adding height/width attr would suffice. 我认为一个简单的每个循环,增加height / width attr就足够了。 Unfortunately this doesn't seem to work 不幸的是,这似乎不起作用

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

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

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

When you inspect element you will notice no width/height attr has been added 当您检查元素时,您会发现没有添加宽度/高度属性

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

You need to do your each on the load event, you need to make sure your image has loaded before you check its height and width. 您需要在load事件中进行每个操作,需要在检查图像的高度和宽度之前确保图像已加载。 Also you want to use $(this) instead of index. 另外,您想使用$(this)代替索引。

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

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

    });
});

Problem here is that you try to get the width and height from the index which is just a number and no jQuery object. 这里的问题是您尝试从只是数字而不是jQuery对象的索引中获取宽度和高度。 Try this - it will do the job: 试试这个-它会做的事:

$('body').find('img').each(function(i, elem) {
        var $this = $(this);
        var theWidth = $this.width();
        var theHeight = $this.height();

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

See js fiddle: https://jsfiddle.net/g4nn2pk0/2/ 参见js小提琴: https : //jsfiddle.net/g4nn2pk0/2/

It's because index is real iteration index (eg 1, 2...). 这是因为index是真实的迭代索引(例如1、2 ...)。 Use $(this) or add second parameter to function header function (index, element) {} : 使用$(this)或在函数头function (index, element) {}添加第二个参数:

$.each($('img'), function () {
    $(this).attr({
        width: $(this).width(),
        height: $(this).height()
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM