0

For example, I have lots of images, all images' original width is 100px, but original height is different. How can I add height attribute based on the original height of these images automatically. Such as

<img src="picture.jpg" width="100" height="132">
<img src="picture.jpg" width="100" height="45">
<img src="picture.jpg" width="100" heighst="321">
<img src="picture.jpg" width="100" height="136">
<img src="picture.jpg" width="100" height="214">
......

I try this, I try to get the original height of each images first,

$(document).ready(function() {
$items = $('img');
$.each($items,function(k, v){
    console.log(v.naturalHeight);
    });
  });

it doesn't work

This works sometimes

 $items = $('img');
    $.each($items,function(k, v){

        $(this).load(function(){

            console.log($(this)[0].naturalHeight);
            $(this).attr('height', $(this)[0].naturalHeight);

        });
    });

The problem is that how can I make sure all the images have been loaded before I run the script?

4

4 回答 4

0

If you do not attribute a height, the image will keep its original proportion.

Otherwise, you can do it with JavaScript, like this :

function loaded() {
    var img = document.getElementById("imgID");
    img.style.height = img.height;
}

EDIT : If you don't have IDs on your images :

function loaded() {
    var images = getElementsByTagName(img);

    for(i = 0; i < images.length; i++) {
        images[i].style.height = img.height;
    }
}
于 2013-11-04T13:20:59.073 回答
0

Easiest implementation would be to wait for all the images to load, and then setting the attribute using JavaScript (I notice you're using jQuery).

$(window).load(function(){

    $.each($('img'), function(){

        // Set the height, hard-style!
        $(this).attr('height', $(this).height());

    });

});

Obviously, there are other - arguably better - ways to do this (like setting each image's height as it loads), but this should suffice.


Have a look at the imagesLoaded jQuery plugin and maybe wrap the above $.each() in one of it's methods, e.g.:

imagesLoaded( '#yourContainer', function() {

    $.each($('img'), function(){

        $(this).attr('height', $(this).height());

    });

});
于 2013-11-04T13:34:11.220 回答
0
(function(){
     $("img.adjust-image").height("100px");
})()

$('img.adjust-image') returns array of all <img>elements that has class=adjust-image class attribute. So We can add the height property for all the images that goes under it.

于 2013-11-04T13:48:19.657 回答
-1

You don't need to add height attribute at all, only width, and image will scale automatically.

于 2013-11-04T13:16:45.600 回答