如何创建Javascript横幅在不同的时间切换图片

How do I create a Javascript banner switches pictures at different times?

本文关键字:时间 何创建 创建 Javascript      更新时间:2023-09-26

我有一个横幅,里面有10张图片。我知道如何设置超时,以便图片每隔一定的秒切换一次,但我如何设置计时器,根据我希望单个图片显示的时间来更改图片。

例如:我希望图片1显示10秒,图片2显示3秒,图片3显示15秒。

到目前为止,这是我的代码:(它以5秒的相等间隔更改所有图像。

Javascript:

        window.onload = rotate;        
         var thisAd = 0;        
         var adImages = new Array("Images1/Picture10","Images1/Picture1","Images1  /Picture2","Images1/Picture3","Images1/Picture4","Images1/Picture5","Images1/Picture6","Images1/Picture7","Images1/Picture8","Images1/Picture9");
function rotate(){              
          thisAd++;
          if(thisAd == adImages.lengh){
            thisAd = 0;
          }     
          document.getElementById("adBanner").src = adImages[thisAd];       
          setTimeout(rotate, 5 * 1000);
}

制作一个时间数组来匹配您的图像。:

var adTimes = new Array(1000,5000,2000.....)

使用计时器中的值

setTimeout(rotate, 5 * adTimes[thisAd]);

您可以将图片存储到具有两个属性的对象中:一个用于URL,另一个用于延迟,然后使用它。

var adImages = [
    {
        url:"img1.png",
        delay: 5
    },
    {
        url:"img2.png",
        delay: 3
    }
];

然后你可以使用这些属性:

var image = adImages[thisAd];
document.getElementById("adBanner").src = image.url;
setTimeout(rotate, image.delay * 1000);

由于计时没有逻辑,因此无法创建通用算法。所以你必须为每个广告切换/else-if。
一个周期后,您还必须重置计数器thisAd

var time;
if(thisAd>9)thisAd=0;
if(thisAd==0)time=10;
else if(thisAd==1)time=3;
else if(thisAd==2)time=15;
...
setTimeout(rotate, time * 1000);