【问题标题】:onclick: picture does not changeonclick:图片没有变化
【发布时间】:2017-11-05 13:42:06
【问题描述】:

我的目标是通过单击按钮随机更改图像。我找到了一个可以做到这一点的 sn-p,但我想训练我的技能并努力完成它,这就是我目前所得到的:

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

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

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>

【问题讨论】:

  • 您将 imageCount 更改为 0,因此它不再是一个数组,您不能再应用 indexOf。为避免这种情况,只需在开头添加您的 console.log
  • 如果您想重置imageCount,只需执行imageCount = [];
  • 谢谢,将 imageCount 设置为 [] 而不是 0,错误就消失了。但问题是,当我单击按钮时没有任何反应,仍然存在..

标签: javascript image random


【解决方案1】:

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

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

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);


}
#imageWrapper {
  height: 200px;
  outline: solid black 1px;
}
<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>

【讨论】:

  • 对不起,我还没有发布我的 css。我确实有身高。这是75vh。当我加载页面时,会显示在 CSS 中设置的带有 URL 的背景图像。 (如图所示)
  • 但是这种方式可以吗?
  • 它正在工作,没有看到任何“错误” - 所以是的,没关系。 :)
猜你喜欢
  • 1970-01-01
  • 2015-03-28
  • 1970-01-01
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-02
  • 2012-09-24
相关资源
最近更新 更多