使用JavaScript查找图像的高度-图像加载错误

Finding height of image using JavaScript - image load error

本文关键字:图像 加载 错误 高度 JavaScript 查找 使用      更新时间:2023-09-26

我似乎无法在Typo3网站上使用Javascript找到图像的高度。

基本上我有javascript运行在一个$(document).ready(function () {。它在页面上查找图像并查找其高度&,然后根据结果执行操作。

有时有效,有时无效。通常,我得到一个宽度值,但没有高度值。我怀疑这是因为浏览器还没有完成图片的加载。

为了解决这个问题,我包含了一个2秒的延迟,以确保img在寻找其高度之前被加载。但这并不是一个很好的解决问题的方法,尤其是当有人下载速度较慢的时候。

在执行操作之前,我如何检查图像是否已完全加载?

下面是一些HTML:

<div class="resize-thumb-img">
    <img src="#.jpg" />
</div>
<div class="resize-thumb-img">
    <img src="#.jpg" />
</div>
<div class="resize-thumb-img">
    <img src="#.jpg" />
</div>

和一些JS:

$(document).ready(function () {
    setTimeout(myFunctionX, 2000);
    function myFunctionX() {
        $(".resize-thumb-img img").each(function(){  //for each image
            console.log("working on image: "+$(this).width() +"x"+$(this).height());
            /* MORE WORK HERE */
        });
    }
});

控制台日志可以给出235x420235x00x0等结果

我找到了一个解决方案,我认为在这种情况下有帮助。它检查图像的宽度是否为"0"。如果是,它等待1秒,然后再次尝试。如果不是0,它就调用之前的函数。在第一个if语句中包含|| null可能会有用-我没有在所有浏览器上测试过。

$(document).ready(function () {
    checkLoadState();
    function checkLoadState()   //checks to see if images are loaded before continuing
    {
        if ($(".resize-thumb-img img").width() != "0")
        {
            console.log("Images loaded. Resizig...");
            myFunctionX();
        }
        else
        {
            console.log("Waiting for images to load.");
            setTimeout(checkLoadState, 1000); // check again in a second
        }
    }
    function myFunctionX() {
        $(".resize-thumb-img img").each(function(){  //for each image
            console.log("working on image: "+$(this).width() +"x"+$(this).height());
            /* MORE WORK HERE */
        });
        }
});

你可以试试下面这个:

$('img').each(function() {
    $(this).attr('height',$(this).height());
    $(this).attr('width',$(this).width());
});

这将帮助您使用jquery找到图像的高度

如果您可以控制服务器端脚本,难道您不能简单地将位图的大小与其文件名一起存储在数据库中吗?然后可以设置IMG元素的WIDTH和HEIGHT属性。

你需要做的是为任何尚未加载的图像绑定一个函数到load事件,就像这样

function processImage(imageElement){
    // do your stuff here
    var img=$(imageElement);
    console.log("working on image: "+img.width() +"x"+img.height());
}
$(document).ready(function () {
    // iterate through the images
    $(".resize-thumb-img img").each(function(){
        var img = $(this);
        if(img.width()==0 || img.height()==0){
            // image has not fully loaded yet, so process it once loaded
            img.on('load',function(){processImage(this);})
        }else{
           // image is loaded so process the image straight away
            processImage(this);
        }
    })
})