Javascript代码第一次不能工作

Javascript code not working first time around

本文关键字:工作 不能 第一次 代码 Javascript      更新时间:2023-09-26

我希望不要混淆大家,但我不能弄清楚这个。我有一个我自己写的灯箱脚本,我试着设置边距,高度和宽度,这样灯箱总是垂直居中。

第一次加载图像时,页边距不正确,图像显示在页面之外。第二次加载很好。这个问题似乎在Chrome (Linux)中更加一致。

我肯定有一个逻辑问题,所以任何帮助将非常感激。谢谢你。

    image = lightbox.childNodes[0];
    boxHeight = window.innerHeight;
    boxWidth = window.innerWidth;
    imgHeight = image.height;
    imgWidth = image.width;
    image.style.maxHeight = (boxHeight-100)+'px';
    imgHeight = image.height;  //Do this again to correct for max height
    imgWidth = image.width;
    if(imgWidth >= (boxWidth-50) || imgHeight >= (boxHeight-50)){
        lightbox.style.width="70%";
        image.style.width = "100%";
        imgHeight = image.height;
        imgWidth = image.width;
    }
    lightbox.style.top = (boxHeight/2)+'px';
    lightbox.style.marginTop = ((-1)*(imgHeight/2))+'px';
    lightbox.style.left = (boxWidth/2)+'px';
    lightbox.style.marginLeft = ((-1)*(imgWidth/2))+'px'; 
    lightbox.style.display = 'block';
    fadeEffect.init(lightbox, 1, 100); //Fade In

无法正常工作,因为图像尚未完全加载。像这样修改:

image = lightbox.childNodes[0];
boxHeight = window.innerHeight;
boxWidth = window.innerWidth;
image.onload = function(){ // Here is the trick
    imgHeight = image.height;
    imgWidth = image.width;
    image.style.maxHeight = (boxHeight-100)+'px';
    imgHeight = image.height;  //Do this again to correct for max height
    imgWidth = image.width;
    if(imgWidth >= (boxWidth-50) || imgHeight >= (boxHeight-50)){
        lightbox.style.width="70%";
        image.style.width = "100%";
        imgHeight = image.height;
        imgWidth = image.width;
    }
    lightbox.style.top = (boxHeight/2)+'px';
    lightbox.style.marginTop = ((-1)*(imgHeight/2))+'px';
    lightbox.style.left = (boxWidth/2)+'px';
    lightbox.style.marginLeft = ((-1)*(imgWidth/2))+'px'; 
    lightbox.style.display = 'block';
    fadeEffect.init(lightbox, 1, 100); //Fade In
}

看这里,有更传统的方式:Javascript图像onload事件绑定
和这里:JavaScript/jQuery事件监听器在所有浏览器的图像加载