2015-11-07 211 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之间的非常小的“区域”。