每次進入頁面,背景都換一張圖——這個小效果能讓站點瞬間靈活起來。原理並不複雜:由伺服器端腳本掃描指定的圖片目錄,隨機挑一張出來,再把它的路徑塞進 CSS 的 background 屬性。以下示範用 ASP 搭配 CSS 完成。
關鍵在於先取得目標文件夾的 Files 集合與文件總數,用 Rnd 配 Randomize 算出一個隨機序號,再遍歷集合取出對應的那個文件,最後把它的檔名拼成可用的相對路徑。
Const IMGS_DIR = "/images" '設定圖片文件夾的地址,隨機顯示該文件夾內任一張圖片
Dim objFSO, objFolderObject, objFileCollection, objFile
Dim intFileNumberToUse, intFileLooper
Dim objImageFileToUse
Dim strImageSrcText
Set objFSO = Server.CreateObject("scripting.FileSystemObject")
Set objFolderObject = objFSO.GetFolder(Server.MapPath(IMGS_DIR))
Set objFSO = Nothing
Set objFileCollection = objFolderObject.Files
Set objFolderObject = Nothing
Randomize()
intFileNumberToUse = Int(objFileCollection.Count * Rnd) + 1
intFileLooper = 1
For Each objFile in objFileCollection
If intFileLooper = intFileNumberToUse Then
Set objImageFileToUse = objFile
Exit For
End If
intFileLooper = intFileLooper + 1
Next
Set objFileCollection = Nothing
strImageSrcText = IMGS_DIR & objImageFileToUse.Name
Set objImageFileToUse = Nothing
#pic{
width: 400px;
height: 300px;
background: url(<%= strImageSrcText %>) no-repeat;
margin: 2em auto;
}
第一,這段樣式必須直接寫在頁面的 header 區,不能抽到外部 CSS 檔裡。因為 <%= %> 屬於伺服器端語法,獨立的 .css 檔不會經過 ASP 解析器處理,變數無從替換,最後只會原樣輸出成一串亂碼路徑。
第二,Randomize 與隨機取號在每次頁面請求時只跑一次,所以效果是「每次進入頁面換一張」,而不是同一頁內反覆跳動。
把目錄裡的圖片尺寸盡量統一,並確保該文件夾只放可直接當背景的圖片檔;否則一旦混入非圖片資源,隨機中獎的就是一塊空白。若希望同一使用者短時間內看到穩定背景、同時降低伺服器磁碟讀取次數,可以把結果寫進 Cookie 或 Session reuse 一段時間。