在完全加载之前获取图像高度

在完全加载之前获取图像高度

本文介绍了在完全加载之前获取图像高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够使用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).

这篇关于在完全加载之前获取图像高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 02:42