利用 JavaScript 動態修改 background-position,讓背景圖片以斜向持續移動,營造落葉飄動、雲層流動等視差滾動效果。無需 CSS 動畫,相容舊版瀏覽器。
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312">
<title>網頁特效--背景斜向移動</title>
</head>
<body bgcolor="#FFFFFF" background="/edu/img/js/0910/bg.gif">
<script>
// 全域設定
const backgroundImg = '/edu/img/js/0910/bg.gif';
const speed = 10; // 移動間隔(ms),數值越小越流暢
let hPos = 0, vPos = 0;
const movert = 1; // 水平位移量
const movedn = 1; // 垂直位移量
// 瀏覽器檢測(舊版寫法,現代可省略)
const browserName = navigator.appName;
const browserVer = parseInt(navigator.appVersion);
if (browserName !== 'Netscape' || browserVer >= 4.5) {
function moveback() {
// 邊界重置邏輯
if (movert !== 0 && hPos > 0) hPos = -100000;
if (movedn !== 0 && vPos > 0) vPos = -100000;
hPos += movert;
vPos += movedn;
document.body.style.backgroundPosition = `${hPos}px ${vPos}px`;
document.body.style.backgroundImage = `url("${backgroundImg}")`;
document.body.style.backgroundRepeat = 'repeat';
setTimeout(moveback, speed);
}
moveback();
}
</script>
</body>
</html>
核心在於定時器持續更新 background-position: x y:
hPos、vPos 累加位移量setTimeout 遞迴呼叫形成動畫迴圈現代瀏覽器建議使用 CSS Animation,效能更佳、不阻塞主執行緒:
<style>
.diagonal-bg {
width: 100vw;
height: 100vh;
background: url('/path/to/leaves.png') repeat;
animation: diagonalMove 20s linear infinite;
}
@keyframes diagonalMove {
0% { background-position: 0 0; }
100% { background-position: 500px 500px; }
}
</style>
<div class="diagonal-bg"></div>
will-change: background-position 優化prefers-reduced-motion 尊重用戶動畫偏好<div class="parallax-layers">
<div class="layer layer-back" style="background: url(bg1.png); animation-duration: 60s;"></div>
<div class="layer layer-mid" style="background: url(bg2.png); animation-duration: 40s;"></div>
<div class="layer layer-front" style="background: url(bg3.png); animation-duration: 20s;"></div>
</div>
不同圖層設定不同動畫速度,產生立體景深感。
transform: translate3d() 代替 background-position 可啟用 GPU 加速setTimeout 回調中執行複雜運算requestAnimationFrame 替代 setTimeout