【问题标题】:How to solve the append value from counter?如何解决计数器的附加值?
【发布时间】:2016-06-08 09:52:05
【问题描述】:

我有一个计数器 javascript:

function animateSun() {
  var $elie = $("#sun");
  $({
    degree: 0
  }).animate({
    degree: 360
  }, {
    duration: 190999,
    easing: 'linear',
    step: function(val) {
      now = Math.round(val);
      if ((now == 5) || (now == 10) || (now == 15)) //increament the value on every 5 value
      {
        var i = 0;
        $('#tam').text(i += 1);
      }
      $elie.css({
        transform: 'rotate(' + now + 'deg)'
      });
      $('#demo').text('sec:' + now);
    },


  });
}
animateSun();
#sun {
  position: absolute;
  width: 55px;
  height: 55px;
  border: 1px solid red;
  background-color: orange;
  opacity: 0.9;
  border-radius: 100%;
  text-align: center;
  top: 50%;
  left: 50%;
  animation: round 3s infinite linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p id="demo"></p>
<p id="tam">0</p>
<p id="sun">sun</p>

计时器正在运行。在时间值达到5 以在#tam 上添加1 然后接下来达到10 #tam 添加1 更改2 上的值。但它不起作用。请帮我。如何在#demo 上的每 5 个值更改时增加 #tam 的值。提前致谢。

【问题讨论】:

  • 您需要将计数器定义为全局变量。

标签: javascript jquery html css counter


【解决方案1】:

您可以尝试以下方法。将Math.floor() 应用到step/5

function animateSun() {
  var $elie = $("#sun");
  $({
    degree: 0
  }).animate({
    degree: 360
  }, {
    duration: 190999,
    easing: 'linear',
    step: function(val) {
      now = Math.round(val);
      $('#tam').text(Math.floor(val/5));
      $elie.css({
        transform: 'rotate(' + now + 'deg)'
      });
      $('#demo').text('sec:' + now);
    },


  });
}
animateSun();
#sun {
  position: absolute;
  width: 55px;
  height: 55px;
  border: 1px solid red;
  background-color: orange;
  opacity: 0.9;
  border-radius: 100%;
  text-align: center;
  top: 50%;
  left: 50%;
  animation: round 3s infinite linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p id="demo"></p>
<p id="tam">0</p>
<p id="sun">sun</p>

【讨论】:

  • 太好了。谢谢@rejith
【解决方案2】:

按照 Rejith 的建议,将计数器值保存在全局变量中。目前,您每次都将计数器设置为 0,然后将其递增,因此结果始终为 1。

var counter = 0;
function animateSun() {
  var $elie = $("#sun");
  $({
    degree: 0
  }).animate({
    degree: 360
  }, {
    duration: 190999,
    easing: 'linear',
    step: function(val) {
      now = Math.round(val);
//          if ((now == 5) || (now == 10) || (now == 15)) //increment the value on every 5 value
      if( now % 5 == 0 )
      {
        $('#tam').text(counter++);
      }
      $elie.css({
        transform: 'rotate(' + now + 'deg)'
      });
      $('#demo').text('sec:' + now);
    },


  });
}
animateSun();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多