我尝试使用jQuery或Javascript在一个页面上获得更多img
的宽度和高度,我尝试了很多选项,例如:
height = this.naturalHeight
和
height = this.height
和
height = this.actualHeight
但没有任何作用。我总是得到0的高度。
所以问题是:为什么不起作用, 如何运作良好?
以下是代码:(已编辑为最佳答案)
$(document).ready(function(){
$('img.albums').load(function(){
var width = $(this).width();
var height = $(this).height();
if(width > height){
$(this).addClass('landscape');
};
});
});
答案 0 :(得分:0)
为图像提供ID 然后
$("imageID").height();
$("imageID").width();
或简单地整合此
此
$(this).height();
$(this).width();
答案 1 :(得分:0)
你可以尝试这个来获得图像的原始尺寸:
var image = $("img")[0];
$("<img/>").attr("src", $(img).attr("src")).load(function() {
var pic_real_width = this.width;
var pic_real_height = this.height;
});
$(this).width()不适用于内存映像。
答案 2 :(得分:0)
如果你在页面中查询图像,你通常会得到0。
作为测试,一旦页面加载(及其中的图像),打开控制台,使用querySelector(或$或其他)抓取元素,然后获取尺寸。看看你得到了什么。
答案 3 :(得分:0)
尝试使用:
$(document).ready(function(){
$('img.albums').each(function(){
var width = $(this).width();
var height = $(this).height();
if(width > height){
console.log("Width:", width, "height:", height)
$(this).addClass('landscape');
console.log("Hoi")
};
});
});
答案 4 :(得分:0)
如果您使用Jquery,那么您应首先参考图像:
HTML code:
<h2>Spectacular Mountains</h2>
<img id='myImage' class='dummyClass' src="pic_mountain.jpg" alt="Mountain View" style="width:304px;height:228px">
JS via ids
$('#myImage').width()
$('#myImage').height()
JS通过类选择器
$('.dummyClass').width()
$('.dummyClass').height()