我希望不要混淆别人,但我无法弄清楚这一点。 我有自己编写的灯箱脚本,我正在尝试设置边距,高度和宽度,以便框始终垂直居中。
第一次加载图像时,边距不正确,图像显示在页面外。第二次加载很好。 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
答案 0 :(得分: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 event binding
在这里:JavaScript/jQuery event listener on image load for all browsers