【问题标题】:Javascript Text SlideshowJavascript 文本幻灯片
【发布时间】:2013-10-04 22:35:36
【问题描述】:

我正在尝试使用 JavaScript 和/或 jQuery 将文本添加到 div 中,然后每隔 10 秒将该文本更改为不同的文本 - 这有点像纯文本的幻灯片。这是我的代码:

<div id="textslide"><p></p></div>

<script>

var quotes = new Array();

quotes[0] = "quote1";
quotes[1] = "quote2";
quotes[2] = "quote3";
quotes[3] = "quote4";
quotes[4] = "quote5";

var counter = 0;

while (true) {
    if (counter > 4) counter = 0;
    document.getElementById('textslide').firstChild.innerHTML = quotes[counter];
    counter++;
    setTimeout( // not sure what to put here, 500); // Want to delay loop iteration
}

</script>

【问题讨论】:

  • setTimeout 的第一个参数是一个函数。 setTimeout 只是递归地调用该函数。所以在你的情况下,只需将js代码放在一个函数中,然后将该函数的名称写为第一个arg。

标签: javascript jquery html loops slideshow


【解决方案1】:

HTML:

<div id="textslide"><p></p></div>

JavaScript/jQuery:

var quotes = [
    "quote1",
    "quote2",
    "quote3",
    "quote4",
    "quote5",
    ];

var i = 0;

setInterval(function() {
$("#textslide").html(quotes[i]);
    if (i == quotes.length) {
        i = 0;
    }
    else {
        i++;
    }
}, 10 * 1000);

Working demo here

【讨论】:

    【解决方案2】:

    这是一个简单的 JS 建议

    function loop() {
        if (counter > 4) counter = 0;
        document.getElementById('textslide').firstElementChild.innerHTML = quotes[counter];
        counter++;
        setTimeout(loop, 500);
    }
    loop();
    

    演示here

    如果你想使用 jQuery 你可以使用这个:$('#textslide p:first').text(quotes[counter]);

    演示here

    【讨论】:

      【解决方案3】:

      而不是while,使用:

      setInterval(function () {
          //do your work here
      }, 10000);
      

      【讨论】:

      • 不是setIntervale,而是setInterval
      【解决方案4】:

      使用一个函数并在 body onload 上调用它

      <html>
          <head>
              <script>
              var counter = 0;
      
              function changeText()
              {
              var quotes = new Array();
      
              quotes[0] = "quote1";
              quotes[1] = "quote2";
              quotes[2] = "quote3";
              quotes[3] = "quote4";
              quotes[4] = "quote5";
      
              if (counter > 4)
                  {
                  counter = 0;
                  }
      
              document.getElementById("textslide").innerHTML = quotes[counter];
      
              setTimeout(function(){changeText()},10000);
              counter ++;
              }
              </script>
          </head>
          <body onload="changeText();">
              <p id="textslide"></p>
          </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 2015-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-12
        • 1970-01-01
        • 2019-12-06
        • 2017-12-26
        相关资源
        最近更新 更多