在jQuery和PrototypeJS中查找未知的图像维度

时间:2013-05-05 09:19:06

标签: jquery prototypejs dimension

bar1

我想在px中找出此图像的尺寸。

在jQuery中

var h = $("img").height();
var w = $("img").width();
alert(h +"px", w +"px");

在PrototypeJS中

var h = $('img').getHeight();
var w = $('img').getWidth();
alert(h);
alert(w);

使用这两个我得到的尺寸为20px和1350px,每个图像的原始尺寸都不同。

2 个答案:

答案 0 :(得分:0)

因此,您希望获得图像的实际大小,而不是它呈现给Web浏览器的大小? 如果是这种情况,这些代码可能会对您有所帮助:

var img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = $("#myimg").attr('src');

参考此处:How do I get actual image width and height using jQuery?

答案 1 :(得分:0)

这是因为$('img')会定位您DOM中的每个图片,20px1350px是您第一张图片的尺寸。在这种情况下,您需要使用each()

$("img").each(function() {
    $(this).click(function() {
        var w = $(this).width(),
            h = $(this).height();
        alert(h +"px " + w +"px");
    });
});

Fiddle

但我建议您为图片分类,而不是仅选择纯<img>标记:

<img class="image" />

然后你可以这样做:

$(".image").click(function() {
    var w = $(this).width(),
        h = $(this).height();
    alert(h +"px " + w +"px");
});

<强> Fiddle