setInterval一个图像功能

时间:2018-01-13 01:37:20

标签: javascript jquery html function

我已经获得了这样的代码,当它改变随机生成的图像时,会使淡化和淡出效果变为黑色:

var imgs = new Array("https://store.vtxfactory.org/wp-content/uploads/2018/header/1.jpg","https://store.vtxfactory.org/wp-content/uploads/2018/header/2.jpg","https://store.vtxfactory.org/wp-content/uploads/2018/header/3.jpg","https://store.vtxfactory.org/wp-content/uploads/2018/header/4.jpg","https://store.vtxfactory.org/wp-content/uploads/2018/header/5.jpg","https://store.vtxfactory.org/wp-content/uploads/2018/header/6.jpg");

function changeOverlay() {
    $('#overlay').animate({opacity: 1,}, 1000);
    $('#overlay').animate({opacity: 0,}, 1000);
}

setTimeout(
  function changeBg() {
    var imgUrl = imgs[Math.floor(Math.random()*imgs.length)];
    $('#masthead').css('background-image', 'url(' + imgUrl + ')');
  }, 3000);

function changeBackgroundSmoothly() {
    $('#masthead').animate(0, changeBg);
}

setInterval(changeOverlay,2000);
setInterval(changeBackgroundSmoothly,2000);

问题是,图像只是第一次旋转,我怎样才能像#overlay那样循环?

你可以在这里有一个视觉概念:https://store.vtxfactory.org

感谢。

1 个答案:

答案 0 :(得分:0)

您可以在控制台中看到参考错误。

首先更改setTimeout方法

var changeBg = function() {
    var imgUrl = imgs[Math.floor(Math.random()*imgs.length)];
    $('#masthead').css('background-image', 'url(' + imgUrl + ')');
}

setTimeout(changeBg, 3000);