Keep website theme the same.. cookies?

泪湿孤枕 提交于 2019-12-08 11:08:50

问题


I think I will need to use javascript to do this so I put it here on stack overflow. So, I have two themes for my website, the only difference is that one is a solid colour (background), the other a repeated image, so I didn't make separate css files for them. I have two links in the navigation bar that change it (with javascript). In the css file its the solid colour, so when ever the page loads it starts out as that. When the image theme link is clicked, it sets the document.body.backgroundImage to the image, and when the solid colour theme link is pressed it just sets the background image to "" (empty), so that you can see the colour again. So how can I make the theme persistent, not changing when ever the user goes to another page, as well as when they return another time. Thanks.

EDIT: I can use either PHP or javascript.


回答1:


If you're using all javascript and don't have any serverside code to work with, here's a JS example to set and read a cookie:

Add this function to your JS, then run it when the theme is changed:

function set_theme(name){
  document.cookie='sel_theme='+name+';';
  }//so, run set_theme('whatevername'); when it is set by the user

To read the cookie and set the theme on page load (using jQuery or similar $(document).ready() would be better than onload, though, but here's a straight js/dom example)

 window.onload=function(){
var cookie_pos=document.cookie.indexOf('sel_theme=');//locate value in cookie
if(cookie_pos!=-1){//if string was found
  var cookie_flavor=substr(cookie_pos+10,document.cookie.indexOf(';',cookie_pos));//extract the value of the cookie
  /*then run your already existing change theme function using the extracted name*/
  }    



回答2:


You can use a session to keep track of the user's preferences on the serverside. When the user comes back on and has a theme selected (which you can determine from the session variables) then the server will deliver HTML that has backgroundImage set instead of a solid color. When the user toggles preferences you can send out an ajax request that updates the session variables.



来源:https://stackoverflow.com/questions/1616943/keep-website-theme-the-same-cookies

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