使背景图像动态化并每隔几秒更改一次

making a background image dynamic and change every few seconds

我的代码在做什么:

我想做的事情:


<div class="text-center background">

    <p>come content</p>

    <img id="image" src="~/images/baseball.jpg">
    
    <script type = "text/javascript">
        var image = document.getElementById("image");
        var currentPos = 0;
        var images = ["/images/baseball.jpg", "/images/basketball.jpg", "/images/football.jpg", "/images/soccerball.jpg"], i = 0;

        function changeimage()
        {
            if (++currentPos >= images.length)
                currentPos = 0;

            image.src = images[currentPos];
        }
        setInterval(changeimage, 3000);
    </script>

</div>

<style>
.background{
    background-image: url(/images/basketball.jpg); //<<<-----this line needs to be dynamic
    background-repeat: no-repeat;
    background-size: cover;
    height: 1000px;
}
</style>

我知道我可能需要稍微重组我的代码。我只是不知道如何去做有背景的。使用普通图像标签很容易,因为我只是将新图像路径重新分配给旧 ID。

附加信息:

框架:.netcore-mvc

bootstrap: 4.6

只需设置背景元素的样式即可,与您当前的解决方案几乎相同:

There's a good solution for this on SO: [Changing background-image with JavaScript]

<div id="background" class="text-center background">

    <p>come content</p>
        
    <script type = "text/javascript">
        var background = document.getElementById("background");
        var currentPos = 0;
        var images = ["/images/baseball.jpg", "/images/basketball.jpg", "/images/football.jpg", "/images/soccerball.jpg"], i = 0;

        function changeimage()
        {
            if (++currentPos >= images.length)
                currentPos = 0;

            background.style.backgroundImage = "url(" + images[currentPos] + ")";
        }
        setInterval(changeimage, 3000);
    </script>

</div>

此解决方案是纯粹的 HTML Javascript,如果您想 运行 服务器上的计时逻辑,图像轮播控件和基于组件的解决方案会有所帮助,但是javascript是一个很简单的解决问题的方法。