我有一个关于加载根据一天中的时间或日期更改 CSS 的 JavaScript 的问题。
问题:如何缓存图像,以免它们从一个页面加载到另一个页面?脚本工作正常,并根据一天中的时间将类添加到正文和标题中。但是,当用户单击网站的下一页时,它会重新加载相同的 CSS 类,并导致网站在加载 CSS 之前闪烁为白色。
我已将脚本放在页面底部和页眉中。然而它仍然在加载脚本的每个页面上闪烁。是否有办法阻止用户每次从一个页面转到另一个页面时加载脚本?
这是Js代码。
function TimeOfDaySiteChange() {
var d = new Date();
var n = d.getHours();
if (n < 5) {
// midnight
night();
} else if (n > 16 && n < 20) {
// If time is between 5PM – 8PM sunset theme to 'body'
dusk();
} else if (n > 19) {
// If time is 8PM
night();
} else if (n > 8) {
// If time is 9AM
daytime();
} else {
// Else use 'dawn' theme
dawn();
}
}
function dawn() {
jQuery('body').addClass('sunrise_bg');
jQuery('#header_masthead').addClass('sunrise_masthead_bg');
}
function daytime() {
jQuery('body').addClass('day_bg');
jQuery('#header_masthead').addClass('day_masthead_bg');
}
function dusk() {
jQuery('body').addClass('sunset_bg');
jQuery('#header_masthead').addClass('sunset_masthead_bg');
}
function night() {
jQuery('body').addClass('night_bg');
jQuery('#header_masthead').addClass('night_masthead_bg');
}
function init() {
TimeOfDaySiteChange();
}
window.onload = init;
我也试过没有window.onload
最佳答案
最好的办法是将它作为您 body 中的第一件事,然后删除 window.onload
。您需要稍微调整您的 css,以便您只更改 body
上的类:
.sunrise_bg #header_masthead{
而不是在 #header_masthead
上上课。
然后运行 TimeOfDaySiteChange()
作为您体内的第一件事。
通过使用 onload
,您可以在应用类之前等待整个页面加载。
或者,如果您使用的是 html5,则可以更改代码以将类添加到 html
元素并将您的 javascript 放在文档的 head
早期.这可能会稍微快一些。
关于javascript - 根据日期时间或一天中的时间更改 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16281832/