準備一組背景圖像:
首先,準備幾個背景圖像,並將它們的URL存儲在一個JavaScript數組中。
使用JavaScript隨機選擇圖像:
使用JavaScript來隨機選擇一個圖像並應用到背景。
應用CSS樣式:
使用CSS來設置背景圖像的樣式。
以下是具體的代碼:
HTML
代碼: 選擇全部
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>隨機背景圖像</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>歡迎來到我的網站</h1>
<script src="script.js"></script>
</body>
</html>
代碼: 選擇全部
body {
margin: 0;
padding: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
font-family: Arial, sans-serif;
color: white;
text-shadow: 2px 2px 4px #000000;
}
代碼: 選擇全部
// 定義背景圖像的URL數組
const backgrounds = [
'url("path/to/your/image1.jpg")',
'url("path/to/your/image2.jpg")',
'url("path/to/your/image3.jpg")',
'url("path/to/your/image4.jpg")',
'url("path/to/your/image5.jpg")'
];
// 隨機選擇一個背景圖像
const randomIndex = Math.floor(Math.random() * backgrounds.length);
const randomBackground = backgrounds[randomIndex];
// 設置背景圖像
document.body.style.backgroundImage = randomBackground;
HTML:
標準的HTML文檔結構,包含引用CSS和JavaScript文件。
CSS:
設置body元素的背景樣式,使其能夠顯示全屏背景圖像。
使用background-size: cover來確保背景圖像覆蓋整個視窗。
使用background-position: center來確保背景圖像居中。
使用background-repeat: no-repeat來確保背景圖像不重複。
JavaScript:
創建一個包含多個背景圖像URL的數組。
使用Math.random()生成一個隨機索引,選擇一個隨機的背景圖像。
將隨機選擇的背景圖像應用到body元素的背景樣式中。
通過這種方式,每次刷新頁面時,您都會看到一個不同的背景圖像。請確保將圖像路徑正確替換為您實際的圖像路徑。