Javascript代码第一次不起作用
我希望不要把人们搞糊涂,但我想不出这一点。 我有一个我自己写的lightbox脚本,我正在尝试设置边距、高度和宽度,以便框始终垂直居中 第一次加载图像时,边距不正确,图像显示在页面外。第二次装的很好。这个问题在Chrome(Linux上)中似乎更为一致 我确信在某个地方存在逻辑问题,因此非常感谢您的帮助。多谢各位Javascript代码第一次不起作用,javascript,css,logic,Javascript,Css,Logic,我希望不要把人们搞糊涂,但我想不出这一点。 我有一个我自己写的lightbox脚本,我正在尝试设置边距、高度和宽度,以便框始终垂直居中 第一次加载图像时,边距不正确,图像显示在页面外。第二次装的很好。这个问题在Chrome(Linux上)中似乎更为一致 我确信在某个地方存在逻辑问题,因此非常感谢您的帮助。多谢各位 image = lightbox.childNodes[0]; boxHeight = window.innerHeight; boxWidth = wind
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
}
看这里,有更传统的方式:
此处:由于图像仍未完全加载,因此无法工作。更改如下:
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
}
看这里,有更传统的方式:
这里:我绝对不会得到这个。非常感谢你,这是一种享受。我绝对不会得到它的。非常感谢你,我请客。