如何将高度属性添加到img标签?

时间:2013-11-04 13:13:19

标签: javascript

例如,我有很多图像,所有图像的原始宽度都是100像素,但原始高度不同。如何自动根据这些图像的原始高度添加高度属性。如

<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">
......

我试试这个,我试着先得到每个图像的原始高度,

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

它不起作用

这有时有效

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

        $(this).load(function(){

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

        });
    });

问题是如何在运行脚本之前确保已加载所有图像?

4 个答案:

答案 0 :(得分:0)

您根本不需要添加高度属性,只需要添加宽度,图像会自动缩放。

答案 1 :(得分:0)

如果您没有属性高度,图像将保持其原始比例。

否则,您可以使用JavaScript执行此操作:

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

编辑: 如果您的图片上没有ID:

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

    for(i = 0; i < images.length; i++) {
        images[i].style.height = img.height;
    }
}

答案 2 :(得分:0)

最简单的实现是等待加载所有图像,然后使用JavaScript设置属性(我注意到你正在使用jQuery)。

$(window).load(function(){

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

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

    });

});

希望这有帮助!

显然,还有其他 - 可以说更好 - 的方法(比如在加载时设置每个图像的高度),但这应该足够了。


查看imagesLoaded jQuery插件,并将上面的$.each()包含在其中一种方法中,例如:

imagesLoaded( '#yourContainer', function() {

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

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

    });

});

答案 3 :(得分:0)

(function(){
     $("img.adjust-image").height("100px");
})()

$('img.adjust-image')返回具有<img> class属性的所有class=adjust-image元素的数组。因此,我们可以为其下的所有图像添加height属性。