我發現可以使用Javascript動態更改CSS的網站http://www.thesitewizard.com/javascripts/change-style-sheets.shtml 就像它將具有2個CSS一樣,您可以單擊其中一個並更改設計的整個網站。但我的問題是,例如我改變它成爲一個替代的CSS然後重新加載它會改變回原來的CSS。我能做些什麼來使它保持我選擇的CSS?這裏是代碼如何使用JavaScript動態更改級聯樣式表(CSS)
這是JavaScript
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
// *** TO BE CUSTOMISED ***
var style_cookie_name = "theme" ;
var style_cookie_duration = 30 ;
// *** END OF CUSTOMISABLE SECTION ***
function switch_style (css_title)
{
// You may use this script on your site free of charge provided
// you do not remove this notice or the URL below. Script from
// http://www.thesitewizard.com/javascripts/change-style-sheets.shtml
var i, link_tag ;
for (i = 0, link_tag = document.getElementsByTagName("link") ;
i < link_tag.length ; i++) {
if ((link_tag[i].rel.indexOf("stylesheet") != -1) &&
link_tag[i].title) {
link_tag[i].disabled = true ;
if (link_tag[i].title == css_title) {
link_tag[i].disabled = false ;
}
}
set_cookie(style_cookie_name, css_title,
style_cookie_duration);
}
}
function set_style_from_cookie()
{
var css_title = getCookie(style_cookie_name);
alert(css_title);
if (css_title.length) {
switch_style(css_title);
}
}
function set_cookie (cookie_name, cookie_value,
lifespan_in_days, valid_domain)
{
alert(cookie_value)
// http://www.thesitewizard.com/javascripts/cookies.shtml
var domain_string = valid_domain ?
("; domain=" + valid_domain) : '' ;
document.cookie = cookie_name +
"=" + encodeURIComponent(cookie_value) +
"; max-age=" + 60 * 60 *
24 * lifespan_in_days +
"; path=/" + domain_string ;
}
function get_cookie (cookie_name)
{
var cookie_string = document.cookie ;
alert(cookie_string)
var re = new RegExp("(^|;)[\s]*" + cookie_name + "=([^;]*)");
if (cookie_string.length != 0) {
var cookie_value = cookie_string.match (re);
alert(cookie_value)
return decodeURIComponent (cookie_value[2]) ;
}
return '' ;
}
set_style_from_cookie()
CSS
這是形式
<form>
<input type="submit"
onclick="switch_style('blue');return false;"
name="theme" value="Blue Theme" id="blue">
<input type="submit"
onclick="switch_style('pink');return false;"
name="theme" value="Pink Theme" id="pink">
</form>
它說,我要穿上合適的信息設置cookie部分
function set_cookie (cookie_name, cookie_value,
lifespan_in_days, valid_domain)
,所以我把它改爲
function set_cookie ("style", "theme",
7, "myanimesekai.com")
但什麼發生的是,它不會工作,如果我改變了它成。有人可以告訴我,如何解決這個問題?所有我想的是,如果用戶選擇了一個樣式它甚至會留下來作爲時,他/她重新載入頁面或去我的網站的另一個頁面
哦,順便說一句,我已經包括了
<body onload="set_style_from_cookie()">
部分但它仍然無法正常工作
希望一些幫助謝謝你,Godbless和對不起我那可憐的語法
難道你確認cookie實際上正在設置? – cimmanon
是的,我做了.......... – user3182950