Javascript代码第一次不能工作
Javascript code not working first time around
我希望不要混淆大家,但我不能弄清楚这个。我有一个我自己写的灯箱脚本,我试着设置边距,高度和宽度,这样灯箱总是垂直居中。
第一次加载图像时,页边距不正确,图像显示在页面之外。第二次加载很好。这个问题似乎在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事件监听器在所有浏览器的图像加载
相关文章:
- AngularJS UI路由器不能像ng路由器那样工作
- HTML5音频加载和播放获胜'我不能在iPad上工作
- JS可以在Chrome中工作,但不能在Firefox中工作
- javascript扫雷器floodfill算法不能正常工作
- JavaScript指令不能像我想象的那样工作
- Facebook登录按钮没有'不能在Firefox上工作
- jQuery Datepicker可以在Safari中工作,但不能在FF或Chrome中工作
- javascript没有´我不能在joomla 3.0中工作
- 用javascript将script元素附加到头部;铬不能工作
- jQuery函数不能只在一个页面上工作
- 为什么这个代码不能正常工作
- 为什么jquery悬停在jsfiddle中可以工作,而在我的html布局中却不能
- 为什么我的JavaScript在Safari上的严格模式下不能正常工作
- 为什么Turbolinks不能正常工作?Rails应用程序
- jQuery dosn'内联函数不能按预期工作
- 为什么这个javascript工作不能正确地分配.cells[] ?
- 谷歌应用引擎云端点:OAuth2不工作.不能加载api
- 输入焦点不工作/不能选择单选按钮-引导
- LocalStorage不能在iPhone上工作-不能在私人浏览
- 工作不能代替生活