每次進入頁面從指定資料夾隨機選取一張圖片作為背景。核心邏輯在 ASP 端掃描資料夾、隨機抽取檔名,再輸出至 CSS background:url()。
<head> 區塊)<%
Const IMGS_DIR = "/images"
Dim objFSO, objFolder, objFiles, objFile
Dim intPick, intLoop, objPicked, strImgSrc
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(Server.MapPath(IMGS_DIR))
Set objFiles = objFolder.Files
Set objFSO = Nothing
Set objFolder = Nothing
Randomize()
intPick = Int(objFiles.Count * Rnd) + 1
intLoop = 1
For Each objFile In objFiles
If intLoop = intPick Then
Set objPicked = objFile
Exit For
End If
intLoop = intLoop + 1
Next
strImgSrc = IMGS_DIR & objPicked.Name
Set objFiles = Nothing
Set objPicked = Nothing
%>
<style> 區塊,不可放外部檔)#pic {
width: 400px; height: 300px;
background: url(<%= strImgSrc %>) no-repeat;
margin: 2em auto;
}
注意:ASP 輸出的變數需在同頁內嵌樣式中使用,外部 CSS 無法解析伺服器端變數。