讓網頁背景圖在每次刷新時隨機變換,能給用戶帶來新鮮感。實現思路很簡單:用隨機數拼湊出背景圖的文件名,再動態設置到 body 的背景樣式中。前提是提前準備好一批命名規律的圖片,例如 bg_1.jpg、bg_2.jpg 等。
<style>
body{
padding: 0;
background-attachment: fixed;
background-clip: border-box;
background-color: #666666;
background-origin: padding-box;
background-position: center top;
background-repeat: no-repeat;
background-size: cover;
width: 100%;
background-image: url("");
}
</style><script type="text/javascript">
$(document).ready(function(){
var random_bg = Math.floor(Math.random() * 6 + 1);
var bg = 'url(images/new_feed/bg_' + random_bg + '.jpg)';
$("body").css("background-image", bg);
});
</script>這裡的關鍵是 Math.random() 生成 0 到 1 之間的隨機小數,乘以 6 後取整再加 1,就能得到 1 到 6 的隨機整數,正好對應 bg_1.jpg 到 bg_6.jpg 這六張背景圖。使用時只需把圖片放到指定目錄,並根據實際圖片數量調整隨機數的範圍即可。此外,background-size: cover 能讓背景圖自適應覆蓋整個屏幕,呈現更好的視覺效果。