萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

ASP + CSS 實現隨機背景圖片輪換

每次進入頁面從指定資料夾隨機選取一張圖片作為背景。核心邏輯在 ASP 端掃描資料夾、隨機抽取檔名,再輸出至 CSS background:url()。

ASP 代碼(置於 <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
%>

CSS 代碼(同頁 <style> 區塊,不可放外部檔)

#pic {
  width: 400px; height: 300px;
  background: url(<%= strImgSrc %>) no-repeat;
  margin: 2em auto;
}

注意:ASP 輸出的變數需在同頁內嵌樣式中使用,外部 CSS 無法解析伺服器端變數。

copyright © 萬盛學電腦網 all rights reserved