2013-12-22 46 views
-1

嗨,我正在爲一個朋友的網站工作。她想爲每個季節使用不同的樣式表;一個用於冬季,春季,夏季和秋季。該網站的風格取決於季節

我在考慮以下方法... 我已經爲每個季節使用style.css構建網站,現在我所要做的就是在一年中的時間段內加載適當的style.css 。

但如何做到這一點?

+0

,你將不得不使用一個服務器端語言如PHP,以便做的一些檢查日期並致電適當的css –

+1

@Matías不,你不必那樣做 – scrblnrd3

+0

@ scrblnrd3,well no;它不一定是服務器端,但必須做一些事情(客戶端或服務器端)來檢測季節,這是通過評估日期來完成的。但無論如何,如果沒有JavaScript或某種服務器端解決方案(無論可能選擇什麼或可用),這是不可能的。 –

回答

1

你可以使用替代樣式

<link rel="stylesheet" type="text/css" title="summer" href="summer.css"> 
<link rel="alternate stylesheet" type="text/css" title="spring" href="spring.css"> 
<link rel="stylesheet" type="text/css" title="fall" href="fall.css"> 
<link rel="alternate stylesheet" type="text/css" title="winter" href="winter.css"> 

,然後創建一個腳本

function setActiveStyleSheet(title) { 
    var links=document.getElementsByTagName("link"); 
    for(var i=0; i<styles.length; i++) { 
    style=styles[i]; 
    if(style.getAttribute("rel").indexOf("style") != -1 && style.getAttribute("title")) { 
     style.disabled = true; 
     if(style.getAttribute("title") == title){ 
      style.disabled = false; 
     } 
    } 
    } 
} 

然後到檢測的季節,你可以使用

var month=new Date().getMonth(); 
if(month<2 || month==11){ 
    setActiveStyleSheet("winter"); 
}else if(month<5){ 
    setActiveStyleSheet("spring"); 
}else if(month<8){ 
    setActiveStyleSheet("summer"); 
}else if(month<11){ 
    setActiveStyleSheet("fall"); 
} 

很明顯,可以使賽季選擇更準確,但那會給你至少一個初步的賽季

+0

Thanx ..那是快的 我會研究這個選項。再次感謝。 – XpDieto

+0

這一個作品,直到他似乎選擇summer.css我錯過了什麼? – XpDieto

+0

我是否在webdomein中測試了這個?或者這也應該離線工作? – XpDieto

2

我鼓勵您使用PHP,因爲用戶可能已禁用JavaScript。

這將是我的做法:

PHP:

//season.php file 
header("Content-type: text/css"); 

function getSeason() 
{ 
    $season_dates = array('/12/21'=>'winter', 
         '/09/21'=>'autumn', 
         '/06/21'=>'summer', 
         '/03/21'=>'spring', 
         '/12/31'=>'winter'); 

    foreach ($season_dates as $key => $value) // Loop through the season dates 
    { 
     $season_date = date("Y").$key; 
     if (strtotime("now") > strtotime($season_date)) // If we're after the date of the starting season 
     { 
      return $value; 
     } 
    } 
} 

$season = getSeason(); 

echo file_get_contents("$season.css"); 

HTML:

<link rel="stylesheet" type="text/css" href="season.php"> 
+0

這種方法很簡短。我喜歡。 但它似乎沒有工作。我製作了php文件。並將其鏈接到html中。像我建議我錯過了什麼? – XpDieto

+0

請參閱編輯:嘗試添加'header(「Content-type:text/css」);' –