简体   繁体   中英

Add width and height attr to all images

I need width and height attributes added to all images on a page via javascript/jquery. This is due to a tool our systems use. I thought a simple each loop, adding height/width attr would suffice. Unfortunately this doesn't seem to work

DEMO 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/

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. Also you want to use $(this) instead of index.

$(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. 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/

It's because index is real iteration index (eg 1, 2...). Use $(this) or add second parameter to function header function (index, element) {} :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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