问题描述
我需要能够使用jQuery在图像#imageHero
完全加载到页面之前获取图像的高度.然后,我需要将div #imageDiv
的高度设置为要加载的#imageHero
的高度.
I need to be able to use jQuery to get the height of an image #imageHero
before it has fully loaded into the page. I then need to set the height of a div #imageDiv
to be the height of the #imageHero
which is being loaded.
我需要在创建页面时尽快发生这种情况...目前,我用于将div #imageDiv
设置为图像#imageDiv
高度的代码正在缓慢进行,页面加载看起来很奇怪. ..
I need this to happen ASAP when the page is created... currently the code I am using to set the div #imageDiv
to the height of the image #imageDiv
is happening to slowly and the page load looks odd...
有什么建议吗?
推荐答案
如评论中所述,这已经得到了解答,尽管在纯JavaScript中不是JQuery.我已将答案修改为:
As mentioned in the comments, this has already been answered here, although in pure JavaScript not JQuery. I have adapted that answer to:
- 使用JQuery
- 使用静态图片
- 创建了一个可以调用的简单函数
这是功能...
function getImageSize(img, callback){
img = $(img);
var wait = setInterval(function(){
var w = img.width(),
h = img.height();
if(w && h){
done(w, h);
}
}, 0);
var onLoad;
img.on('load', onLoad = function(){
done(img.width(), img.height());
});
var isDone = false;
function done(){
if(isDone){
return;
}
isDone = true;
clearInterval(wait);
img.off('load', onLoad);
callback.apply(this, arguments);
}
}
您可以使用图像元素和接受宽度和高度参数的回调来调用该函数...
You can call the function with an image element, and a callback accepting width and height arguments...
getImageSize($('#imageHero'), function(width, height){
$('#imageDiv').height(height);
});
小提琴 -要查看完整效果,请确保图像不在您的缓存中(随机添加到图像源).
Fiddle - To see the full effect make sure the image is not in your cache (append a random to the image source).
这篇关于在完全加载之前获取图像高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!