You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

问题:现有JavaScript代码无法将随机图片设为CSS背景

解决随机背景图加载问题

你的代码核心问题是CSS里的url(myPicture)无法识别DOM元素ID,它会把myPicture当作一个文件路径去查找,自然加载失败。直接通过JavaScript修改body的背景样式就能解决,不需要中间的img元素中转。

修改后的完整代码:

<script>
window.onload = choosePic;
var myPix = [
  "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/bgfiles/cool_stuff_anim.gif",
  "https://ptgmedia.pearsoncmg.com/images/chap4_9780321996701/elementLinks/04fig15.jpg"
];
function choosePic() {
  var randomNum = Math.floor(Math.random() * myPix.length);
  document.body.style.backgroundImage = `url(${myPix[randomNum]})`;
}
</script>

<style>
body {
  /* 可选添加背景适配样式,提升显示效果 */
  background-size: cover;
  background-position: center;
  min-height: 100vh;
  margin: 0;
}
</style>

关键修改点:

  • 移除了无用的img注释代码,直接通过JS操作document.body.style.backgroundImage设置背景图
  • 将数组写法从new Array()简化为更简洁的字面量写法[]
  • 补充了背景图适配样式,让图片在不同屏幕尺寸下显示更合理

内容的提问来源于stack exchange,提问作者repeekyraid cero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 12:05:21