如何每x秒显示一个新图像?

时间:2016-11-04 14:50:39

标签: javascript

尝试使用JavaScript设置间隔计时器,我不确定如何将图像放入数组中。
我尝试了几种不同的方法,但无法使其发挥作用。

var myImage = document.getElementById("mainImage");

var imageArray = [img class="irc_mi ix3z7xWjrSdc-pQOPx8XEepE" alt="Image result for baseball images" style="margin-top: 70px;" src="http://totalsportscomplex.com/wp-content/uploads/2014/09/baseball-pic.jpg" onload="google.aft&&google.aft(this)" width="626" height="415",
img class="irc_mi ix3z7xWjrSdc-pQOPx8XEepE" alt="Image result for baseball images" style="margin-top: 70px;" src="http://totalsportscomplex.com/wp-content/uploads/2014/09/baseball-pic.jpg" onload="google.aft&&google.aft(this)" width="626" height="415",
img class="irc_mi ix3z7xWjrSdc-pQOPx8XEepE" alt="Image result for baseball images" style="margin-top: 70px;" src="http://totalsportscomplex.com/wp-content/uploads/2014/09/baseball-pic.jpg" onload="google.aft&&google.aft(this)" width="626" height="415"]

var imageIndex = 0;

function changeImage() {
    myImage.setAttribute("src",imageArray[imageIndex]);
  imageIndex++;
  if(imageIndex >= imageArray.length) {
  indexImage = 0;
  }
}

setInterval(changeImage,5000);

事先感谢,我也是新人,并且确实试图寻找答案但却找不到答案。

2 个答案:

答案 0 :(得分:2)

有几件事

  1. 您的数组需要是一个字符串数组:

  2. 您将src属性设置为包含多个来源的整个字符串

  3. indexImage未定义

    var myImage = document.getElementById("mainImage");
    
    var imageArray = [
        "http://totalsportscomplex.com/wp-content/uploads/2014/09/baseball-pic.jpg",
        "http://totalsportscomplex.com/wp-content/uploads/2014/09/baseball-pic.jpg",
        "http://totalsportscomplex.com/wp-content/uploads/2014/09/baseball-pic.jpg"
    ]
    
    var imageIndex = 0;
    
    function changeImage() {
        myImage.setAttribute("src", imageArray[imageIndex]);
        imageIndex++;
        if (imageIndex >= imageArray.length) {
            imageIndex = 0;
        }
    }
    
    setInterval(changeImage, 5000);
    

答案 1 :(得分:0)

首先它不是负面评论但是,你只是不能把你想要的东西扔进阵列。他们可以持有字符串,数字,函数,对象,......

  • 由于所有其他变量相同,因此首先创建一个静态图像



<img id="mainImage"  class="irc_mi ix3z7xWjrSdc-pQOPx8XEepE" alt="Image result for baseball images" style="margin-top: 70px;" onload="google.aft&amp;&amp;google.aft(this)" width="626" height="415"/>
&#13;
&#13;
&#13;

&#13;
&#13;
  function changeImage() {
        myImage.setAttribute("src",imageArray[imageIndex]);
      imageIndex++;
      if(imageIndex >= imageArray.length) {
      indexImage = 0;
      }
    }
&#13;
&#13;
&#13;