0

我希望不要让人们感到困惑,但我无法弄清楚这一点。我有一个我自己编写的灯箱脚本,我正在尝试设置边距、高度和宽度,以便盒子始终垂直居中。

第一次加载图像时,边距不正确,图像出现在页面外。第二次加载正常。这个问题在 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
4

1 回答 1

3

它不起作用,因为图像仍未完全加载。像这样改变它:

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 Image onload 事件绑定
和这里:JavaScript/jQuery event listener on image load for all browsers

于 2013-06-18T04:56:31.750 回答