使用.addclass函数制作骰子辊不起作用

时间:2018-09-27 09:19:52

标签: javascript jquery html css

我希望首先加载id=die,然后单击按钮“单击我”以加载CSS中设计为“ die1”,“ die2”的指定类,依此类推

function roll() {
  var die = Math.floor(Math.random() * 6);
  if (die == 1)
    $('#die').addClass('die1');
  else if (die == 2)
    $('#die').addClass('die2');
  else if (die == 3)
    $('#die').addClass('die3');
  else if (die == 4)
    $('#die').addClass('die4');
  else if (die == 5)
    $('#die').addClass('die5');
  else
    $('#die').addClass('die6');
}
#die {
  width: 300px;
  border: 5px solid black;
  padding: 25px;
  margin: 25px;
}

.die1 {
  width: 300px;
  border: 5px solid green;
  padding: 25px;
  margin: 25px;
}

.die2 {
  width: 300px;
  border: 5px solid pink;
  padding: 25px;
  margin: 25px;
}

.die3 {
  width: 300px;
  border: 5px solid violet;
  padding: 25px;
  margin: 25px;
}

.die4 {
  width: 300px;
  border: 5px solid yellow;
  padding: 25px;
  margin: 25px;
}

.die5 {
  width: 300px;
  border: 5px solid red;
  padding: 25px;
  margin: 25px;
}

.die6 {
  width: 300px;
  border: 5px solid blue;
  padding: 25px;
  margin: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="die"></div>
<button onclick="roll()">Click me!</button>

我不知道为什么不调用必需的类? 当我尝试在js中打印变量“ die”时,它工作正常。

1 个答案:

答案 0 :(得分:6)

您的CSS规则应更具体,因为标识符比类更具体,例如:

#die.die1 {
#die.die2 {
...

然后您的JS函数可能很简单:

$('#die').removeAttr('class').addClass('die' + die);

删除上一个类,然后添加新的类。

注意:由于您没有1类,因此可能需要将最小值作为die0添加到随机数:

var die = Math.floor(Math.random() * 6) + 1;

function roll() {
  var die = Math.floor(Math.random() * 6) + 1;

  $('#die').removeAttr('class').addClass('die' + die);
}
#die {
  width: 300px;
  border: 5px solid black;
  padding: 25px;
  margin: 25px;
}

#die.die1 {
  width: 300px;
  border: 5px solid green;
  padding: 25px;
  margin: 25px;
}

#die.die2 {
  width: 300px;
  border: 5px solid pink;
  padding: 25px;
  margin: 25px;
}

#die.die3 {
  width: 300px;
  border: 5px solid violet;
  padding: 25px;
  margin: 25px;
}

#die.die4 {
  width: 300px;
  border: 5px solid yellow;
  padding: 25px;
  margin: 25px;
}

#die.die5 {
  width: 300px;
  border: 5px solid red;
  padding: 25px;
  margin: 25px;
}

#die.die6 {
  width: 300px;
  border: 5px solid blue;
  padding: 25px;
  margin: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="die"></div>
<button onclick="roll()">Click me!</button>

如果要避免所有这些类,可以从JS代码中更改border-color,例如:

function roll() {
  var colors = ["green", "pink", "violet", "yellow", "red", "blue"];
  var die = Math.floor(Math.random() * colors.length);

  $('#die').css('border-color', colors[die]).addClass('die' + die);
}
#die {
  width: 300px;
  border: 5px solid black;
  padding: 25px;
  margin: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="die"></div>
<button onclick="roll()">Click me!</button>