如何使用JavaScript为动态变化的图像背景提供过渡效果

时间:2015-12-16 05:54:23

标签: javascript html5 css3

我有一个页面,其中特定div的背景图像不断动态变化。我想能够对图像进行一些过渡效果。该页面运行在纯JavaScript上。这是我的代码:

var bgArray = ["images/1.jpg", "images/2.jpg", "images/3.jpg"];
var i = 0;

function myFunction() {
    setInterval(function() {
        if (i == 3) {
            i = 0;
        }
        var urlString = bgArray[i];
        var x = document.getElementById("myDiv");
        x.style.background = "url(" + bgArray[i] + ") no-repeat";
        x.style.backgroundSize = "1366px";
        i = i + 1;
    }, 6000);
}

myFunction();

谢谢。

2 个答案:

答案 0 :(得分:0)

#myDiv {
  transition: background 1s;
}

答案 1 :(得分:0)

HTML代码

<div id = "myDiv"></div>

CSS代码

#myDiv{
   width: <yourDivWidth>;
   height: <yourDivHeight>;
   background-size: cover;
  }

Javascript代码

var box = document.getElementById("myDiv");    
var imagesList = ["url('images/1.jpg')", "url('images/2.jpg')", "url('images/3.jpg')"];

i = 0;
box.style.backgroundImage = imagesList[i];

function nextImg(){
   box.style.backgroundImage = imagesList[i+1];
   //box.style.width = "1366px";
   //box.style.height = "1366px";
   //declare your width and height of div in css and give background-size: cover;.
   i = i+1;
   if(i == imagesList.length){
     i = 0;
     box.style.backgroundImage = imagesList[i];
   }
}

window.onload = setInterval(nextImg, 6000);

等待6秒钟,看到背景图像发生变化 如果你想在前6秒设置背景图像,那么你可以在你的CSS中设置它 评论你是否有任何疑问。