我正在尝试显示随机图片。我不知道为什么它不起作用。请帮忙。
我的部分内容:
<h2>
Roll Dice!
</h2>
<input type="button" onClick="rollDice()" value="Roll Dice!" />
<p></p>
<img src="images/one.png" class="dice" id="one"/>
<img src="images/two.png" class="dice" id="two"/>
<img src="images/three.png" class="dice" id="three"/>
<img src="images/four.png" class="dice" id="four"/>
<img src="images/five.png" class="dice" id="five"/>
<img src="images/six.png" class="dice" id="six"/>
我的部分js:
function getRandomNumber(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function rollDice ()
{
var dicenum = getRandomNumber(1,6);
if(dicenum === 1) {
document.getElementsByTagName("img").style.visibility = "hidden";
document.getElementById('one').style.visibility = "visible";
}
else if(dicenum === 2) {
document.getElementsByTagName("img").style.visibility = "hidden";
document.getElementById('two').style.visibility = "visible";
}
else if(dicenum === 3) {
document.getElementsByTagName("img").style.visibility = "hidden";
document.getElementById('three').style.visibility = "visible";
}
else if(dicenum === 4) {
document.getElementsByTagName("img").style.visibility = "hidden";
document.getElementById('four').style.visibility = "visible";
}
else if(dicenum === 5) {
document.getElementsByTagName("img").style.visibility = "hidden";
document.getElementById('five').style.visibility = "visible";
}
else if(dicenum === 6) {
document.getElementsByTagName("img").style.visibility = "hidden";
document.getElementById('six').style.visibility = "visible";
}
}
我的CSS的一部分:
*
{
font-family:Helvetica,sans-serif;
}
.dice
{
visibility:hidden;
}
GitHub上的整个回购:https://github.com/ThatRandomPerson/random-number-thing/ 谢谢!
答案 0 :(得分:1)
为循环图像制作函数:
function hideImages(images){
for(var i = 0;i < images.length;i++){
images[i].style.display = 'none';
}
}
更改:
document.getElementsByTagName("img").style.visibility = "hidden";
document.getElementById('one').style.visibility = "visible";
在任何条件下:
hideImages(document.getElementByTagName('img'));
document.getElementById('one').style.display = 'block';
答案 1 :(得分:0)
document.getElementsByTagName("img").style.visibility = "hidden";
getElementsByTagName
返回一个集合(NodeList)。您不能将样式更改应用于整个列表,您必须循环它们。
如果您只想影响其中一个元素,可以使用getElementsByTagName("img")[0]
选择第一张图片。
使用getElementsByClassName
会更好,因为页面上可能还有其他图片。
示例循环:
var imgs = document.getElementsByClassName("dice");
for (var i=0; i < imgs.length; i++) {
// do stuff with imgs[i]
}