网站背景图片未覆盖



我想在每次网站加载时使用javascript加载随机背景图像。背景应该覆盖全屏。我的两个背景不一样,一个像正方形图像,另一个更短更宽。我希望能够填满整个屏幕,无论选择哪个。我尝试将背景覆盖属性应用于 css,但它似乎失败了。无论如何,短背景都不会拉伸。

更新它现在可以工作了

html{
    height: 100%;
    width: 100%;
}
body{
    margin : 0;
    padding: 0;
    min-height:100%;
    font-size: 17px;    
}
function loadRandomBackground() {
    var backgroundNumber = Math.floor((Math.random() * 2) + 1);
    document.body.style.background = "url('img/bg" + backgroundNumber +  ".jpg')";
    document.body.style.backgroundRepeat = "no-repeat";
    document.body.style.backgroundPosition = "center";
    document.body.style.backgroundSize = "cover";
}

你可以像这样设置正文CSS。无需使用 JS 更改它。

body{
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

最新更新