div的交替背景图像会自动?

时间:2015-01-14 18:04:45

标签: javascript image background carousel intervals

这就是我目前所拥有的,div#hero的三个背景图片在刷新时会发生变化。是否有任何简单的方法来调整它,以便它们在x秒后淡出到备用图像,而不是刷新?

<script type="text/javascript">var imgCount = 3;
    var dir = 'images/';
    var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
    var images = new Array
            images[1] = "1.jpg",
            images[2] = "2.jpg",
            images[3] = "3.jpg",
    document.getElementById("hero").style.backgroundImage = "url(" + dir + images[randomCount] + ")";</script>

1 个答案:

答案 0 :(得分:0)

将代码包装在函数中并使用setInterval方法:

var interval_time = 5000;//in milliseconds
setInterval(your_function,interval_time);
function your_function(){
var imgCount = 3;
    var dir = 'images/';
    var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
    var images = new Array
            images[1] = "1.jpg",
            images[2] = "2.jpg",
            images[3] = "3.jpg",
    document.getElementById("hero").style.backgroundImage = "url(" + dir + images[randomCount] + ")";
}

现在,每个interval_time your_function运行后。