萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

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

前言

讓網頁每次載入隨機顯示指定資料夾中的一張圖片作為背景,可增加視覺變化。本文示範以 ASP 掃描資料夾、CSS 內嵌樣式的輕量實作。

ASP 端:掃描資料夾隨機選取圖片

<%
'===============================================================
' RandomBackground.asp - 產生隨機背景圖片 URL
' 需放在頁面  區塊或母版頁中,不可放入外部 .css 檔
'===============================================================
Const IMGS_DIR = "/images/bg"  ' 相對網站根目錄的圖片資料夾

Dim fso, folder, files, file, randIndex, i, selectedFile, imgUrl
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(Server.MapPath(IMGS_DIR))
Set files = folder.Files
Set fso = Nothing

If files.Count = 0 Then
    imgUrl = IMGS_DIR & "/default.jpg"  ' 後備圖片
Else
    Randomize()
    randIndex = Int(files.Count * Rnd) + 1  ' 1-based 索引
    i = 1
    For Each file In files
        If i = randIndex Then
            Set selectedFile = file
            Exit For
        End If
        i = i + 1
    Next
    imgUrl = IMGS_DIR & "/" & selectedFile.Name
    Set selectedFile = Nothing
End If

Set files = Nothing
Set folder = Nothing
%>

CSS 端:內嵌樣式套用隨機背景

必須放在頁面 <head> 區塊的 <style> 標籤中,因為需使用 ASP 內嵌變數 <%= imgUrl %>。

<head>
  <style type="text/css">
    #random-bg {
      width: 100%;
      height: 400px;               /* 固定高度或 100vh */
      background: url(<%= imgUrl %>) no-repeat center center;
      background-size: cover;      /* 覆蓋模式,保持比例填滿 */
      margin: 0 auto;
    }
  </style>
</head>

HTML 結構

<body>
  <div id="random-bg"></div>
  <!-- 其他頁面內容 -->
</body>

完整整合範例

<%@ Language=VBScript %>
<%
' ... 上述 ASP 掃描代碼放在最頂端 ...
%>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>隨機背景示範</title>
  <style>
    #random-bg {
      width: 100%; height: 100vh;
      background: url(<%= imgUrl %>) no-repeat center center;
      background-size: cover;
    }
    .content { position: relative; z-index: 1; padding: 2rem; color: #fff; text-shadow: 1px 1px 3px #000; }
  </style>
</head>
<body>
  <div id="random-bg"></div>
  <div class="content">
    <h1>歡迎光臨</h1>
    <p>每次重新整理背景圖片都會隨機變化。</p>
  </div>
</body>
</html>

進階擴充建議

  • 前端 JS 輪播:若需無刷新切換,改由 JS 陣列存圖片清單,setInterval 切換 background-image。
  • 效能優化:圖片建議壓縮至 200KB 內,啟用 IIS 靜態內容壓縮與快取標頭。
  • 資料庫驅動:大量圖片時,改存資料庫記錄路徑、權重、啟用狀態,ASP 查詢隨機一筆。
  • 響應式:搭配 picture / srcset 或 CSS 媒體查詢提供不同解析度圖片。

結語

ASP 掃描資料夾 + CSS 內嵌變數,幾十行代碼即可實現隨機背景。關鍵在於:ASP 代碼必須在 HTML <style> 標籤之前執行,讓 <%= imgUrl %> 正確解析為實際圖片 URL。

copyright © 萬盛學電腦網 all rights reserved