2015-02-23 39 views
0

我試圖動畫某一位置之後的數字,但問題是,它在循環的條件一遍又一遍如何動畫數字與if語句的jQuery

我的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> 

我要運行的語句之後的第一次,這就是它的

+0

什麼功能是'animateNumber '? – void 2015-02-23 10:44:20

回答

1

你想是這樣的 - 刪除事件處理函數時條件滿足

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

謝謝工作:) – Daniel 2015-02-23 10:50:37

1

可以使用布爾變量來做出決定的代碼是否已經執行或不:

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 
} 
});