我在脑海中有一个项目,我想要更改基于一天中的时间的样式表。我最初是用php这样做的,但它占用了服务器的时间。考虑到时区差异,这是一种不太理想的体验。
我认为javascript可能是获取用户本地时间的最佳选择,但我不确定该如何编写它。This is similar to what I had in mind,但我想每3-6个小时改变一下风格就会更多。提前感谢您的帮助!
发布于 2012-01-27 22:20:14
你可以这样做:
$stylesheets = array(
'foo.css',
'bar.css',
'baz.css',
// ...
'qux.css'
);
$numStylesheets = count($stylesheets);
if (24 % $numStylesheets !== 0) {
echo 'Number of stylesheets needs to be a factor of 24.';
exit;
}
$hour = (int)date('H', $_SERVER['REQUEST_TIME']);
$changeEveryXHours = 24 / $numStylesheets;
$offset = floor($hour / $changeEveryXHours);
$stylesheet = $stylesheets[$offset];
echo '<link rel="stylesheet" href="', $stylesheet, '" />';
它是动态的,基于您指定的样式表的数量。目前样式表的数量需要是24的倍数(1,2,3,4,6,8,12,24)。您可以通过将代码修改为使用分钟和秒而不是仅使用小时来消除这一要求,但对于今天上午的我来说,这太复杂了。:-)
编辑:以下是JS中的相同脚本:
var stylesheets = [
'foo.css',
'bar.css',
'baz.css',
// ...
'qux.css'
];
if (24 % stylesheets.length != 0) {
alert('Number of stylesheets needs to be a factor of 24.');
return false;
}
var now = new Date();
var hour = now.getHours();
var changeEveryXHours = 24 / stylesheets.length;
var offset = Math.floor(hour / changeEveryXHours);
var stylesheet = stylesheets[offset];
// If you're using jQuery, I think it's something like this:
$('<link>')
.prop({
rel: 'stylesheet',
href: stylesheet
})
.appendTo($('head'));
发布于 2012-01-27 22:05:24
来自以下地址的指南:
http://www.alistapart.com/articles/alternate/
我建议你从标题为“另类”的部分开始阅读
将alternate
属性与函数一起使用:
发布于 2012-01-27 22:20:21
首先,有两个选项:只使用jQuery (JavaScript)或使用jQuery & PHP
如果您在使用PHP之前使用ajax请求向PHP函数发送当前时间,并返回所需的样式表,然后将其放入头部
function do_it()
{
now = new Date();
current_time = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
$.ajax({
type: "POST",
url: "your_php_script.php",
data:{ current_user_time: current_time}
}).done(function( data ) {
//maybe you will need some logic here :)
//and get the old file name
$('link[href^=old_css_file.css]').attr('href',data);
});
}
setInterval(function(){
do_it();
//cal it every 3 hours
}, 10800000);
https://stackoverflow.com/questions/9034311
复制相似问题