DIV CSS 佈局教程網

用 jQuery 實現刷新頁面背景圖片隨機變換
編輯:JQuery特效代碼     

讓網頁背景圖在每次刷新時隨機變換,能給用戶帶來新鮮感。實現思路很簡單:用隨機數拼湊出背景圖的文件名,再動態設置到 body 的背景樣式中。前提是提前準備好一批命名規律的圖片,例如 bg_1.jpg、bg_2.jpg 等。

一、CSS 代碼

<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>

二、jQuery 代碼

<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 能讓背景圖自適應覆蓋整個屏幕,呈現更好的視覺效果。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved