在if/else语句中使用onload函数
Using the onload function in if/else statements
我正试图创建一个页面,根据一天中的时间,图像的位置不同。就像太阳在页面上升起一样,取决于时间——早上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;
};
解决同一个问题有很多方法。选择一个适合你的,但尽可能避免复制粘贴的代码;)
相关文章:
- 在phonegap中为android调用onload函数的最佳方式
- 如何调用表td标记内的Onload函数
- 不执行包含的页面的Javascript onload函数
- 你能停止window.onload函数吗
- 使用多个JavaScript Onload函数
- 如何只使用一次window.onload函数
- 在iframe中禁用onload函数的Javascript
- 如果可能的话,使用jQuery onLoad函数来加载特定的页面
- 将Window Onload函数转换为非阻塞
- JavaScript-如何将onload函数内部定义的变量取到外部
- 为什么window.onload函数未定义
- 特定窗口的onload函数
- 如何同时创建两个Onload函数
- onLoad函数不工作,如何使用BindListener修复它
- javascript onload函数范围查询
- javascript onload函数有效,onresize则无效
- Image.onload 函数为高度和宽度返回零
- 全局传递xhr onload函数的值
- 尽管有onload函数,但替换内部HTML失败
- windows.onload函数不工作