Javascript图像覆盖整个页面

Javascript图像覆盖整个页面,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有以下代码,它是每10秒更改背景图像的函数: $(function() { var body = $(".home"); var backgrounds = [ "url(img/Agure.jpg)", "url(img/Arsenal1.jpg)", "url(img/ManUtd.jpg)", "url(img/stadion.jpg)", ]; var current = 0; function nextBackground() { body.

我有以下代码,它是每10秒更改背景图像的函数:

$(function() {
var body = $(".home");
var backgrounds = [
    "url(img/Agure.jpg)",
    "url(img/Arsenal1.jpg)",
    "url(img/ManUtd.jpg)",
    "url(img/stadion.jpg)",
];
var current = 0;

function nextBackground() {
    body.css(
        "background",
        backgrounds[current = ++current % backgrounds.length]);
    setTimeout(nextBackground, 10000);
}
setTimeout(nextBackground, 10000);
body.css("background", backgrounds[0]);
代码可以工作,但我希望图像始终覆盖整个页面。有些图像太小,无法覆盖整个页面,因此它们只是挨着彼此堆叠。有什么建议可以修改代码吗

HTML和CSS:

<section class="home">
    <div class="centered">
        <div class="h-100 row align-items-center">
        </div>
    </div>
</section>

.home {
    width: 100%;
    height: 100vh;
    background-position: center top;
    background-size: cover;
}

.家{
宽度:100%;
高度:100vh;
背景位置:中上;
背景尺寸:封面;
}

这里的问题是两件事的结合:

  • 您没有使用
    background repeat:no repeat
    ,这意味着图像将平铺以覆盖背景(这仅在图像小于容器时可见,这可能会造成混淆)
  • 您正在JS中设置
    background
    ,而不是
    background image
    ,这将覆盖额外的CSS属性
以下是一个修改版本:

$(函数(){
变量主体=$(“.home”);
变量背景=[
“网址(https://picsum.photos/200/300)",
“网址(https://picsum.photos/100/300)",
“网址(https://picsum.photos/300/300)",
“网址(https://picsum.photos/250/300)",
];
无功电流=0;
函数nextBackground(){
body.css(
“背景图像”,
背景[当前=+当前百分比背景.长度]
);
设置超时(下一个背景,10000);
}
设置超时(下一个背景,10000);
css(“背景图像”,背景[0]);
})
.home{
宽度:100%;
高度:100vh;
背景位置:中上;
背景尺寸:封面;
背景重复:无重复;
}

当图像较小时,浏览器会自动添加多个图像(堆叠在您的箱子中)

尝试在css中添加以下内容以避免它

background-repeat: no-repeat;
也不是写作

body.css("background", backgrounds[0]);


出于好奇,既然CSS动画会是一个更好的选择,为什么你要用JS来完成这个任务呢?我没有好的答案。我对css还不是很熟练。通过使用
body.css(“background”…
你正在用默认值覆盖所有其他
background
属性…你应该只在那里设置背景图像!
body.css("background-image", backgrounds[0]);