所謂隨機背景,就是每次開啟頁面時,從指定的圖片資料夾裡隨機挑一張當背景。這個效果用 ASP 挑檔、CSS 負責鋪陳,兩個技術各司其職,程式碼並不長。
思路很直接:用 FileSystemObject 取得資料夾底下所有檔案,數出總數,隨機取一個序號,再把對應的檔案找出來,最後組出它的相對路徑。
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幾個細節:呼叫 Rnd 之前一定要先 Randomize,否則每次重啟應用程式都會跑出同一串序列;取完物件記得逐一釋放,這是 VBScript 的習慣;路徑記得用 & 串接而不是 +。
#pic {
width: 400px;
height: 300px;
background: url(<%= strImageSrcText %>) no-repeat;
margin: 2em auto;
}關鍵在 background 那行的 <%= %>:伺服器先把變數值輸出成實際路徑,瀏覽器收到的已經是一段完整的 CSS。
也正因如此,這段樣式必須寫在 header 區、由 ASP 即時產生,不能抽到外部的 .css 檔裡——外部檔案不經過 ASP 解析,那個標記只會被當成一段無效的文字。
實作上通常還會加兩道保險:一是只讓特定副檔名(jpg、gif、png)進入隨機池,避免資料夾裡的說明檔被選中;二是準備一張預設背景圖,萬一資料夾是空的也不至於開天窗。