Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用JavaScript为动态更改图像背景提供过渡效果_Javascript_Html_Css - Fatal编程技术网

如何使用JavaScript为动态更改图像背景提供过渡效果

如何使用JavaScript为动态更改图像背景提供过渡效果,javascript,html,css,Javascript,Html,Css,我有一个页面,其中特定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; }

我有一个页面,其中特定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();
谢谢。

HTML代码

#myDiv {
  transition: background 1s;
}
<div id = "myDiv"></div>
等待6秒钟,查看背景图像的变化。
如果您还想设置前6秒的背景图像,则可以在CSS中设置。
如果您有任何疑问,请发表评论

#myDiv{
   width: <yourDivWidth>;
   height: <yourDivHeight>;
   background-size: cover;
  }
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);