onclick:图片不会改变

时间:2017-11-05 13:42:06

标签: javascript image random

我的目标是通过点击按钮随机更改图像。我找到了一个可以做到这一点的代码片段,但我想培养自己的技能,并通过它完成工作,这是我到目前为止所做的:

  1. 当我单击按钮时,第11行的变量没有任何反应,但是当我放入URL而不是变量(从第22行从控制台复制)时,它会转到相应的图片。我不明白......

  2. 当我的“imageCount”已满时,出现错误

  3. var imageCount = [];
    var image = ["img/01.jpg", "img/02.jpg", "img/03.jpeg", "img/04.jpeg"];
    
    function changeImage() {
      var rand = Math.floor(Math.random() * image.length);
      var imageNumber = "\"url('" + image[rand] + "')\""
    
    
      if (imageCount.indexOf(rand) === -1) {
        imageCount.push(rand);
        document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
    
      } else if (imageCount.length === image.length) {
        imageCount = 0;
      } else {
        changeImage();
      }
      console.log(imageNumber);
      console.log(imageCount.indexOf(rand));
      console.log(image[rand]);
      console.log(imageCount);
    
    
    }
    <link href="./style/main.css" rel="stylesheet">
    <div class="wrapper">
      <div class="buttonWrapper">
        <button class="button" onclick="changeImage()">Next Pic</button>
      </div>
    
      <div id="imageWrapper">
        <!--<img src="./img/02.jpg" alt="" id="random">-->
      </div>
    </div>

    Picture: Console and Error message

1 个答案:

答案 0 :(得分:0)

有两件事阻止你的演示代码工作:

  • #imageWrapper没有高度,因此不会显示图片(可能只是因为您的网页缺少CSS)
  • 您将imageCount变量重置为0而不是[]

&#13;
&#13;
var imageCount = [];
var image = ["//baconmockup.com/300/199/", "//baconmockup.com/300/200/", "//baconmockup.com/300/201/", "//baconmockup.com/300/202/"];

function changeImage() {
  var rand = Math.floor(Math.random() * image.length);
  var imageNumber = "url('" + image[rand] + "')"


  if (imageCount.indexOf(rand) === -1) {
    imageCount.push(rand);
    document.getElementById("imageWrapper").style.backgroundImage = imageNumber;

  }

  else if (imageCount.length === image.length) {
    imageCount = [];
  }

  else {
    changeImage();
  }
  console.log(imageNumber);
  console.log(imageCount.indexOf(rand));
  console.log(image[rand]);
  console.log(imageCount);


}
&#13;
#imageWrapper {
  height: 200px;
  outline: solid black 1px;
}
&#13;
<div class="wrapper">
  <div class="buttonWrapper">
    <button class="button" onclick="changeImage()">Next Pic</button>
  </div>

  <div id="imageWrapper">
    <!--<img src="./img/02.jpg" alt="" id="random">-->
  </div>
</div>
&#13;
&#13;
&#13;