在if/else语句中使用onload函数

Using the onload function in if/else statements

本文关键字:onload 函数 语句 if else      更新时间:2023-09-26

我正试图创建一个页面,根据一天中的时间,图像的位置不同。就像太阳在页面上升起一样,取决于时间——早上6点在左下角,早上7点稍微高一点,等等。我对每个部分都使用了一个onload函数,但最后一个onload函数似乎覆盖了所有内容,无论该部分是否为当前时间。如果不是一天中的那个时间,有没有办法取消加载功能?以下是我的脚本要点:

var today = new Date().getHours();
if (today >= 6 && today < 7) {
    document.body.style.background = "lightBlue";
    window.onload = generateSunball;
    function generateSunball() {
        var sunUp=document.getElementById("sunAppear");
        sunUp.style.display='';
        sunUp.style.position='absolute';
        sunUp.style.top='480px';
        sunUp.style.left='30px';
        sunUp.style.width='200px';
        sunUp.style.height='200px';
    }
} 
else if (today >=7 && today < 8) {
    document.body.style.background = "lightBlue";
    window.onload = generateSunball;
    function generateSunball() {
        var sunUp=document.getElementById("sunAppear");
        sunUp.style.display='';
        sunUp.style.position='absolute';
        sunUp.style.top='330px';
        sunUp.style.left='120px';
        sunUp.style.width='200px';
        sunUp.style.height='200px';
    }
}

您正在多次定义function generateSunball,并且这些定义的范围不限于if..else块。最后一个将是剩下的唯一一个。

考虑尝试:

window.onload = function() {
    // do stuff here
};

同样值得注意的是,您可以完全重构代码。类似。。。

switch(today) {
case 6:
    window.onload = ...;
    break;
case 7:
    ...
    break;
...
deafult:
    ...
}

或者,定义具有选项的单个对象:

var sunProperties = {
    "6":{
        "top": "480px",
        "left": "30px"
    },
    "7":{
        "top": "330px",
        "left": "120px"
    }
    ...
};
window.onload = function() {
    var sunUp = document.getElementById('sunAppear');
    sunUp.style.display = "";
    sunUp.style.position = "absolute";
    sunUp.style.width = sunUp.style.height = "200px";
    sunUp.style.top = sunProperties[today].top;
    sunUp.style.left = sunProperties[today].left;
};

解决同一个问题有很多方法。选择一个适合你的,但尽可能避免复制粘贴的代码;)