Javascript current hour to use specific stylesheet?

与世无争的帅哥 提交于 2019-12-25 02:25:22

问题


I use the following code to get the current hour of the client and to know if it's AM or PM:

<script type="text/javascript">
//get client time
var d = new Date();
if(d.getHours() >= 06 && d.getHours() <= 18){
    var dayStatus = "day";
    document.write("day");
}else{
    var dayStatus = "night";
    document.write("night");
}
</script>

I figured out how to find out if it's AM or PM for the client but I want to use different css stylesheet whether it's day or night. How could I do this?

This is what I got in my html HEAD so far which obviously does not work, just need to know how to make it work:

<script type="text/javascript">
if(dayStatus = "day"){
    <link href="includes/style.css" rel="stylesheet" type="text/css" />
}else{
    <link href="includes/style2.css" rel="stylesheet" type="text/css" />
}
</script>

回答1:


You cannot change a (server-side) session using JavaScript. You really need to do this server-side. If you need the clients time, you will need to post it to the server using AJAX. There are, however, two easier ways of doing it:

Client-sided:

if (isDay) {
    document.write('<link type="text/css" rel="stylesheet" href="url/to/day.css" />');
} else {
    document.write('<link type="text/css" rel="stylesheet" href="url/to/night.css" />');
}

Server-sided:

if ($isDay) {
    echo '<link type="text/css" rel="stylesheet" href="url/to/day.css" />';
} else {
    echo '<link type="text/css" rel="stylesheet" href="url/to/night.css" />';
}



回答2:


Why don't you forget the date calculation on the client, and instead (on page load) make an AJAX call to a PHP script that will determine whether or not to start the session?




回答3:


This is possible, will your users be on the same page for a long period of time or be moving around? If they are moving around then simply have the PHP function that will execute on the page load and then determine if to create a new session. Or if not then run a Javascript function on a timer that sends a GET request to a php script which then determines if to create a new session.



来源:https://stackoverflow.com/questions/5870098/javascript-current-hour-to-use-specific-stylesheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!