![](/img/trans.png)
[英]FlexSlider: How to get image height on page load using JS or jQuery?
[英]How to get the true image height using JQuery?
我想加载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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.