如何将以前的值与当前值进行比较

时间:2017-05-09 02:03:00

标签: javascript

我已经创建了一个骰子滚动脚本,但问题是当它绘制相同的数字时它看起来好像没有更改数字。

我想到了问题的两个解决方案,一个是添加某种检查,如果当前值等于之前的值,那么它将显示“再次”字样。

我也想为角色设置动画,但因为它被JS插入,所以似乎忽略了放在容器上的动画。

#rollCount {
  opacity: 0;
  animation-name: fade-in;
  animation-fill-mode: forwards;
  animation-duration: 2s;
}

@keyframes fade-in {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
<h1>Dice Roll</h1>
<h2>Your fate awaits...</h2>
<div id="rollCount"></div>
<button class="" onclick="diceRoll()">Dice Roll</button>

<script>
  function diceRoll() {
    var number = Math.floor(Math.random() * 6) + 1;
    document.getElementById('rollCount').innerHTML = "<h3>" + number + "</h3>";
  }
</script>

2 个答案:

答案 0 :(得分:1)

每次用户点击按钮时创建一个类并添加/删除它。同时将#rollCount的不透明度设置为1,这样当你删除它时它仍会显示。

 <style>
        #rollCount {
            opacity: 1;
        }
        #rollCount.fade-in {
            animation-name: fade-in;
            animation-fill-mode: forwards;
            animation-duration: 2s;
        }

        @keyframes fade-in {
            0% {
                opacity: 0;
            }
            100% {
                opacity: 1;
            }
        }
    </style>
<h1>Dice Roll</h1>
    <h2>Your fate awaits...</h2>
    <div id="rollCount"></div>
    <button class="" onclick="diceRoll()">Dice Roll</button>

<script>
        function diceRoll() {
            var number = Math.floor(Math.random() * 6) + 1;
            document.getElementById('rollCount').className +=' fade-in';
            document.getElementById('rollCount').innerHTML = "<h3>" + number + "</h3>";
            setTimeout(function() {
                document.getElementById('rollCount').classList.remove('fade-in');
            }, 1000)

        }
    </script>

答案 1 :(得分:1)

如果用户连续两次滚动相同的数字并且计算机假设再次显示 ...请尝试此操作...

<h1>Dice Roll</h1>
<h2>Your fate awaits...</h2>
<div id="rollCount"></div>
<button onclick="diceRoll()">Dice Roll</button>

<script>
  function diceRoll() {
   var number = Math.floor(Math.random() * 6) + 1;
   var prev = document.getElementById('rollCount').innerText;
   if(number == parseInt(prev))
     document.getElementById('rollCount').innerHTML = "<h3 class='fade-in' >again</h3>";
   else
     document.getElementById('rollCount').innerHTML = "<h3 class='fade-in' >" + number + "</h3>";
  }
</script>

现在,在元素上添加淡入 ...

@keyframes fadeAnimation {
  0%   { opacity:0; }
  50%  { opacity:.5; }
  100% { opacity:1; }
}
@-o-keyframes fadeAnimation{
  0%   { opacity:0; }
  50%  { opacity:.5; }
  100% { opacity:1; }
}
@-moz-keyframes fadeAnimation{
  0%   { opacity:0; }
  50%  { opacity:.5; }
  100% { opacity:1; }
}
@-webkit-keyframes fadeAnimation{
  0%   { opacity:0; }
  50%  { opacity:.5; }
  100% { opacity:1; }
}
.fade-in {
   -webkit-animation: fadeAnimation 1s;
   -moz-animation: fadeAnimation 1s;
   -o-animation: fadeAnimation 1s;
    animation: fadeAnimation 1s;
}

代码的Jsfiddle:https://jsfiddle.net/bzjg5yo6/