Make JavaScript change background image every 5 seconds

后端 未结 3 1458
温柔的废话
温柔的废话 2021-01-22 08:34

I am trying to change my background image every 5 seconds. How should I go about this?

window.onload = function () {

  function Timer() {
    window.setInterval         


        
3条回答
  •  抹茶落季
    2021-01-22 09:06

    you are accessing style incorrectly

    window.onload = function () {
    
        function changeImage() {   
            var BackgroundImg=["./Img/Bg1.jpg",
                "./Img/Bg2.jpg",
                "./Img/Bg3.jpg",
                "./Img/Bg4.jpg"
            ];
            var i = Math.floor((Math.random() * 4));
            document.body.style.backgroundImage = 'url("' + BackgroundImg[i] + '")';
        }
        window.setInterval(changeImage, 5000);
    }
    

    Also, if possible (usually is) don't pass a string to window.setInterval - use as above

提交回复
热议问题