如何使用if语句jquery对数字进行动画处理

how to animate numbers with if statement jquery

本文关键字:动画 处理 数字 何使用 if 语句 jquery      更新时间:2024-03-12

我试图在某个位置后设置数字动画,但问题是它一次又一次地循环条件

我的JS

 var target = $("#team").offset().top-$(window).height();
 $(document).scroll(function() {
  if ($(window).scrollTop() > target) {
   $('#lines').animateNumber({ number: 165 },500);
  }
 });

我的HTML

  <div id="team"></div>
  <div class="col-lg-3">
      <h3 id="lines">0</h3>
  </div>

我只想第一次运行该语句,这是它的

您想要这样的东西-当条件满足时删除事件处理程序

    var target = $("#team").offset().top-$(window).height();
    $(document).on('scroll', function() {
        if ($(window).scrollTop() > target) {
            $('#lines').animateNumber({ number: 165 },500);
            $(this).off('scroll');
        }
     });

您可以使用布尔变量来决定代码是否已经执行:

var target = $("#team").offset().top-$(window).height();
//declare decision variable to false
var hasanimatenum=false;
$(document).scroll(function() {
 if ($(window).scrollTop() > target && !hasanimatenum) {//also check that decision variable is false
   $('#lines').animateNumber({ number: 165 },500);
   hasanimatenum=true;//set decision variable to true
 }
});