2015-11-07 221 views
1

我搜索了很多這些天,但我沒有設法解決我的問題。滾動到特定的div或id後觸發事件

我有下面的腳本是一個簡單的計數器,從0開始計算一些統計數據。它開始於我的頁面加載時。我想在我滾動到特定的div或id時觸發此事件,但僅觸發一次。我用.one()方法等看了很多例子,但我沒有找到合適的解決方案。

這是我的腳本。

<script type="text/javascript"> 

$.fn.jQuerySimpleCounter = function(options) { 
     var settings = $.extend({ 
     start: 0, 
     end: 100, 
     easing: 'swing', 
     duration: 500, 
     complete: '' 
    }, options); 

    var thisElement = $(this); 

    $({count: settings.start}).animate({count: settings.end}, { 
     duration: settings.duration, 
     easing: settings.easing, 
     step: function() { 
      var mathCount = Math.ceil(this.count); 
      thisElement.text(mathCount); 
     }, 
     complete: settings.complete 
    }); 
}; 

$('.number1').jQuerySimpleCounter({end: 14,duration: 2899}); 
$('.number2').jQuerySimpleCounter({end: 350,duration: 3300}); 
$('.number3').jQuerySimpleCounter({end: 450,duration: 4000}); 
$('.number4').jQuerySimpleCounter({end: 7,duration: 2500}); 

</script> 

那麼我應該添加什麼來觸發它達到某個div或id後...?

+1

也許這會幫助你.. http://stackoverflow.com/questions/1225102/jquery-event-to-trigger-action-when-a-div-is-made-visible –

+0

看看這個插件http://imakewebthings.com/waypoints/guides/getting-started/ –

回答

0

這應該給你你正在尋找的結果是:

$(window).scroll(function (event) { 
    var scroll = $(window).scrollTop(); 
    var one = $('element').position().top; 
    var count = 0; 
    if (scroll > one) { 
    var newCount = count + 1; 
    if (newCount === 1) { 
     //do something 
    }; 
    }; 
}); 
+0

這是實現這個目標的好方法,但現在我只需觸發一次事件,因爲每次我滾動到特定的div時,計數器就會重新開始並再次... – FotisK

+0

編輯的代碼,使其發生一次 –

+0

你的意思..如果(滾動>一){? – FotisK

0

我設法找到一個「好」的解決方案,爲我的作品。做下面的「不太好」的事情。 :)謝謝尼古拉斯的幫助。

<script type="text/javascript"> 

$(window).scroll(function (event) { 
    var scroll = $(window).scrollTop(); 
    var one = $('.tworow').position().top; 
    var two = $('.endrow').position().top; 
    if (scroll > one & scroll < two) { 

$.fn.jQuerySimpleCounter = function(options) { 
     var settings = $.extend({ 
      start: 0, 
      end: 100, 
      easing: 'swing', 
      duration: 500, 
      complete: '' 
     }, options); 

     var thisElement = $(this); 

     $({count: settings.start}).animate({count: settings.end}, { 
      duration: settings.duration, 
      easing: settings.easing, 
      step: function() { 
       var mathCount = Math.ceil(this.count); 
       thisElement.text(mathCount); 
      }, 
      complete: settings.complete 
     }); 
    }; 

$('.number1').jQuerySimpleCounter({end: 14,duration: 2899}); 
$('.number2').jQuerySimpleCounter({end: 350,duration: 3300}); 
$('.number3').jQuerySimpleCounter({end: 450,duration: 4000}); 
$('.number4').jQuerySimpleCounter({end: 7,duration: 2500}); 

    }; 
}); 

當滾動達到一定的div它開始,在那之後我把另一格凡在活動應該結束,用if條件控制它。現在觸發事件的頁面區域是2個div之間的非常小的「區域」。