我写的页面是全天候显示的,并且没有任何交互。我希望CSS根据小时和分钟(即8:30而不是8)进行更改。我发现一个完全基于小时的解决方案,但无法在混合中获得分钟,我还要更进一步一旦它触及触发CSS更改的时间,它也会刷新页面以更改CSS。
var d=new Date();
var twi_am_start = 6;
var twi_am_end = 14;
var twi_pm_start = 14;
var twi_pm_end = 22;
if (d.getHours() >= twi_am_start && d.getHours() < twi_am_end)
document.write('<link rel="stylesheet" href="../css/first.css" type="text/css">');
else if (d.getHours() >= twi_pm_start && d.getHours() < twi_pm_end )
document.write('<link rel="stylesheet" href="../css/second.css" type="text/css">');
else
document.write('<link rel="stylesheet" href="../css/third.css" type="text/css">');
答案 0 :(得分:1)
只需根据您的时间在页面正文中添加一个类:
<body class="morning">
然后将css应用于它:
.morning { background: orange; }
.afternoon { background: lightblue; }
.evening { background: darkblue; }
(为颜色挑选一些随机名称)
答案 1 :(得分:0)
要获得分钟而不是几小时,您可以使用此方法:
var d = new Date();
var n = d.getMinutes();
现在您可以使用脚本进行调整。
答案 2 :(得分:0)
如果您真的希望根据时间更改css文件,请尝试以下操作:
var now = new Date(),
hours = now.getHours(),
minutes = now.getMinutes() + hours * 60,
link = document.createElement('link'),
href;
var TIME_INTERVALS = { // in minutes
AM_START: 6 * 60,
AM_END_PM_START: 14 * 60,
PM_END: 22 * 60
}
var CSS_FILES = {
AM_START: 'first.css',
AM_END_PM_START: 'second.css',
PM_END: 'third.css'
}
link.rel = 'stylesheet';
link.type = 'text/css';
if (minutes > TIME_INTERVALS.AM_START) {
if (minutes > TIME_INTERVALS.AM_END_PM_START) {
if (minutes > TIME_INTERVALS.PM_END) {
// > PM_START hours now
href = CSS_FILES.PM_END;
} else {
// > AM_END_PM_START && < PM_END time
href = CSS_FILES.AM_END_PM_START;
}
} else {
// AM_START - AM_END
href = CSS_FILES.AM_START;
}
} else {
// 00.00 - AM_START
href = CSS_FILES.PM_END;
}
link.href = '../css/' + href;
document.getElementsByTagName('head')[0].appendChild(link);
jsFiddle示例 - https://jsfiddle.net/mvx42L92/