每次单击相同的按钮,都会执行不同的操作

时间:2018-07-03 16:17:44

标签: javascript html css

我在屏幕上有一堆图像,这些图像当前都被CSS隐藏。我在屏幕的正中央也有一个按钮。我希望有一个功能,每次单击它都会取消隐藏其他图像。这似乎超出了我对JavaScript的经验。

1 个答案:

答案 0 :(得分:0)

这可以帮助您开始。您应该已经提供了一些代码。

function showimage() {
  var imgs = document.getElementsByClassName("hidden");
  
  //if there are any images left to show
  if(imgs.length > 0) {
    var img = imgs[Math.floor(Math.random() * imgs.length)];
    img.className = "shown";
  }
}
.hidden {
  display: none;
}

.shown {
  display: unset;
}
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<br />

<button type="button" onclick="showimage()">Click Me!</button>