如何在底部显示 100px 时在滚动时触发 jquery 函数

how to trigger jquery function on scroll when it shows 100px fro the bottom

本文关键字:jquery 函数 滚动 100px 底部 显示      更新时间:2023-09-26

>我的网站上有"有趣的事实"计数器,还有一个jQuery函数,可以动画计数有趣的事实中的数字div.现在,它会在页面加载时触发。我想在用户向下滚动到它时启动它。例如,当div 从屏幕底部出现 100px 时。

这是我的jQuery函数,它在页面加载时开始计数:

(function($) {
    "use strict";
    function count($this){
    var current = parseInt($this.html(), 10);
    current = current + 10; /* Where 50 is increment */ 
    $this.html(++current);
        if(current > $this.data('count')){
            $this.html($this.data('count'));
        } else {    
            setTimeout(function(){count($this)}, 50);
        }
    }           
    $(".stat-count").each(function() {
      $(this).data('count', parseInt($(this).html(), 10));
      $(this).html('0');
      count($(this));
    });
})(jQuery);

这是我尝试在用户向下滚动到它时使其工作:

(function($) {
    "use strict";
    function count($this){
    var current = parseInt($this.html(), 10);
    current = current + 10; /* Where 50 is increment */ 
    $this.html(++current);
        if(current > $this.data('count')){
            $this.html($this.data('count'));
        } else {    
            setTimeout(function(){count($this)}, 50);
        }
    }        


$(window).scroll(function() {
    $(".stat-count").each(function() {

    var imagePos = $(this).offset().top;
    var topOfWindow = $(window).scrollTop();
        if (imagePos < topOfWindow+400) {
          $(this).data('count', parseInt($(this).html(), 10));
          $(this).html('0');
          count($(this));
        }
       }
    }
 })(jQuery);

谢谢!:)

可能是

这样的:

$(window).on('scroll', function(event) {
  if(document.body.offsetHeight - event.pageY <= 100 ) {
   //onscoll effect
}
}