【问题标题】:Javascript Random image, random transition slideshowJavascript 随机图像,随机过渡幻灯片
【发布时间】:2021-01-18 20:07:11
【问题描述】:

我目前有一个图像幻灯片,其中有随机图像,但我似乎无法找到一种方法来阻止图像在开始时加载并应用随机过渡。 有人可以帮忙吗? 谢谢。

pre><html>
   <head>
      <title>change picture</title>
      <script type = "text/javascript">
          function displayNextImage() {
              x = (x === images.length - 1) ? 0 : x + 1;               
              document.getElementById("img").src = images[x];
}
          function startTimer() {
              setInterval(displayNextImage, 4000);
          }
          var trans=[
              
              ]; 
          var images = [
              "https://cosecha-verde.000webhostapp.com/images/Centro/2016-2017/10.png" ,
                "https://cosecha-verde.000webhostapp.com/images/Centro/2016-2017/11.png" ,
                "https://cosecha-verde.000webhostapp.com/images/Centro/2016-2017/12.png" ,
                "https://cosecha-verde.000webhostapp.com/images/Centro/2016-2017/13.png" ,
                "https://cosecha-verde.000webhostapp.com/images/Centro/2016-2017/14.png"
              ], x = -1;
          
      </script>
   </head>
<body onload = "startTimer()">
       <img id="img" src="https://cosecha-verde.000webhostapp.com/images/Centro/2016-2017/1.png" data-transition="slideInLeft" />
   </body>
</html>

【问题讨论】:

  • 图片11和14不存在!

标签: javascript performance image-processing css-transitions slideshow


【解决方案1】:

以下代码从第一张图片开始,然后生成随机索引来选择下一张图片。避免连续两次选择同一张图片。

JS

function displayNextImage() {
    var bkX = x;
    x = (x === images.length - 1) ? 0 : Math.floor(Math.random() * images.length + 1);  

    //If new X is the same as old X and is not the last image, incremnt to avoid the same image twice in a row
    if (bkX === x && x !== images.length)
        x++;
    //If new X is the same as old X but is the last image, decrement
    else if (bkX === x && x === images.length)
        x--;
    console.log("x " + x);

    document.getElementById("img").src = images[x];
}

function startTimer() {
    setInterval(displayNextImage, 4000);
}

var trans=[]; 
var images = [
    "https://cosecha-verde.000webhostapp.com/images/Centro/2016-2017/10.png" ,
    "https://cosecha-verde.000webhostapp.com/images/Centro/2016-2017/11.png" ,
    "https://cosecha-verde.000webhostapp.com/images/Centro/2016-2017/12.png" ,
    "https://cosecha-verde.000webhostapp.com/images/Centro/2016-2017/13.png" ,
    "https://cosecha-verde.000webhostapp.com/images/Centro/2016-2017/14.png"
], 
x = -1;

JSFIDDLEhttps://jsfiddle.net/xentd0fo/1/

【讨论】:

  • 有没有办法给图像添加随机过渡?谢谢。
  • 当我添加更多图像时,幻灯片会卡住。我在数组中添加了 200 张图像,但是在测试时,幻灯片不会继续播放下一张图像。请帮忙。
猜你喜欢
  • 2016-05-04
  • 2016-07-28
  • 1970-01-01
  • 2013-03-10
  • 2016-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多