基本用法
document.getElementById('myDiv').style.backgroundImage = 'url(https://example.com/bg.jpg)';
進階:預載 + 淡入
function setBackground(divId, imgUrl) {
const img = new Image();
img.onload = () => {
const div = document.getElementById(divId);
div.style.backgroundImage = `url(${imgUrl})`;
div.style.opacity = 0;
div.style.transition = 'opacity 0.5s';
requestAnimationFrame(() => div.style.opacity = 1);
};
img.onerror = () => console.error('圖片加載失敗', imgUrl);
img.src = imgUrl;
}
setBackground('myDiv', 'https://example.com/large-bg.jpg');
CSS 配合
#myDiv {
width: 100%; height: 100vh;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}