【问题标题】:Javascript code not working first time aroundJavascript代码第一次无法正常工作
【发布时间】:2013-06-18 04:51:59
【问题描述】:

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

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

【问题讨论】:

    标签: javascript css logic


    【解决方案1】:

    由于图像仍未完全加载,因此无法正常工作。改成这样:

    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

    【讨论】:

    • 我绝对不会得到那个。非常感谢,工作愉快。
    猜你喜欢
    • 2023-03-11
    • 2013-08-06
    • 1970-01-01
    • 2015-12-25
    • 2012-09-10
    • 1970-01-01
    • 2015-09-10
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多