如何在背景上制作随机图像

时间:2016-09-27 17:11:03

标签: jquery html image

我想在我的网站上每5分钟将背景更改为新图像。如果可能的话,我想用jQuery完成这个。

我希望它循环播放3张图片。怎么做?

这是我目前的代码:

<!DOCTYPE html>
<html>
<head>
    <script type='text/javascript' src='jquery-3.1.1.min.js'></script>
    <script type='text/javascript' src='jquery-ui/jquery-ui.js'></script>

    <script type='text/javascript'>
        $(document).ready(function(){
            setInvetval(function(){
        $('body').css('background-image', 'image-path');
    }, 300000);
    });
    </script>
</head>

<body>

</body>
</html>

2 个答案:

答案 0 :(得分:2)

有点不清楚,但我想你需要类似下面的代码,你可以运行它:

$(document).ready(function(){
    // initializing the index
    var actual = 0;

    // interval implementation
    setInterval(function(){     
 
        // setting the image
        $('body').css('background', "url('" + my_image_array[actual] + "')");
        
        // contrilling the index
        if (actual == my_image_array.length) {
          actual = 0;
        } else {
          actual = actual + 1;
        }
        
        // debugging the index
        //console.log(actual);
    }, 800); // 300000, have setted short time for tests
});

// Instantiating array
var my_image_array = new Array();

// Some images in an array structure
my_image_array[0] = 'https://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg';
my_image_array[1] = 'http://static8.depositphotos.com/1003153/893/v/950/depositphotos_8938809-Example-rubber-stamp.jpg';
my_image_array[2] = 'http://thumb7.shutterstock.com/display_pic_with_logo/436114/268701041/stock-vector-example-blue-square-grunge-textured-isolated-stamp-268701041.jpg';
my_image_array[3] = 'http://garsonadvogados.com.br/wp-content/uploads/2015/08/example3.jpg';
my_image_array[4] = 'http://st.depositphotos.com/1023799/2906/v/950/depositphotos_29066941-Grunge-example-rubber-stamp-vector.jpg';
/* basic style to the body */
body{width:100%; height:100%;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>

答案 1 :(得分:0)

请使用下面的脚本代码。

 <script type='text/javascript'>
        $(document).ready(function () {
            var timeout = 300000;
            var i = 1;
            var action = function () {
                // Do stuff here
                if (i < 3) {
                    i++;
                } else {
                    i = 1;
                }
                console.log("image" + i);
                // $('body').css('background', "url('path/image"+i+ "')"); you can possible put your image here.
                setTimeout(action, timeout);
            };
            action();

        });
    </script>

我在其中创建了一个无限工作的递归函数,你可以在你想要设置的时间内更改超时变量。请检查您的浏览器控制台,以便您了解。你必须将你的图像编号的后置修复从1到3,以便它可以按你的需要工作。例如image1,image2和image3

相关问题