我想加载 html ,然后得到真实的图像高度。
$("#cover").html(stuff); //this has the image inside it
$(function(){
console.log($("#cover img").height()); //sometimes it's 0
});
由于某种原因,高度有时为 0。可能是因为图像尚未完全加载,而 JQuery 将其视为 0?如果是这样,我该如何克服?加载图像时是否有回调或其他东西?
我想加载 html ,然后得到真实的图像高度。
$("#cover").html(stuff); //this has the image inside it
$(function(){
console.log($("#cover img").height()); //sometimes it's 0
});
由于某种原因,高度有时为 0。可能是因为图像尚未完全加载,而 JQuery 将其视为 0?如果是这样,我该如何克服?加载图像时是否有回调或其他东西?
您可以使用 jQuery 的 .load() 方法
$('#cover').html(stuff);
$('#cover img').load(function () {
console.log($(this).height());
};
为什么console.log里面有个匿名函数?你试过这个吗?
$("#cover").html(stuff); //this has the image inside it
console.log($("#cover img").height());
//locate the image(s)
$("#cover img").each(function(){
//Build a new Image Object outside the DOM
//that way, CSS won't affect it
var img = new Image();
//add a callback when loaded
img.onload = function(){
//your width and height
//img.width
//img.height
}
//use the image src to load
//use attr() to resolve path issues across browsers
img.src = $(this).attr('src');
});
尝试使用load method
我们可以利用的方法使这项工作也按照我们想要的方式进行。
我们现在遇到的问题是,在 Webkit 浏览器中,jQuery 代码在 DOM 就绪时运行,而 DOM 在图像加载之前就已经就绪。所以代码运行,但由于没有图像可以得到宽度,我们得到 0 作为图像的宽度。我们可以使用 load 方法让代码等到窗口完全加载后再运行。
$(window).load(function() {
console.log($("#cover img").height());
});
尝试使用 attr() 获取高度:-
$("#yourElemengtID").attr('height')
这是我之前使用的一段小代码,希望对您有所
帮助
function MouseIn()
{
var src;
//to get original image size
var img =$(this);// displayed image
var theImage = new Image();// create a cache image
var imgsource =img.attr("src");// take the src of displayed image
theImage.src = imgsource;// give cached image the source of displayed image
var original_height = theImage.height// take height of image from the source
var original_width = theImage.width;//take width of image from the source
// to get the displayed image size
var Image_displaysize_width= img.width();
var Image_displaysize_height= img.height();
}
你不是打算做这样的事情吗?
jQuery("#myImg")[0].naturalHeight
最好还是尽可能不要使用 jQuery 的开销。
document.getElementById('myImg').naturalHeight