当我滚动到特定< div>时,开始执行jQuery函数 [英] Start executing jQuery function when I scroll to a specific <div>

查看:86
本文介绍了当我滚动到特定< div>时,开始执行jQuery函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery脚本,它在页面上显示一个动画计数器,但脚本从页面加载开始,我需要在用户滚动到特定的< div>

I have a jQuery script that shows an animated counter on page, but the script starts on page load, and I need it to be loaded when the user scrolls down to a specific <div>.

<script>
         $({countNum: $('#counter').text()}).animate({countNum: 63  }, {
          duration: 3000,
          easing:'linear',
          step: function() {
            $('#counter').text(Math.floor(this.countNum));
          },
          complete: function() {
            $('#counter').text(this.countNum);

          }
        });
</script>

当我滚动到这个特定的< div>时,需要执行这个脚本;

This script need to be executed when I scroll to this specific <div> on a page.

<div id="counter"></div>


推荐答案

工作演示:http://jsfiddle.net/fedmich/P69sL/

尝试此操作,将您的代码添加到start_count ...然后确保添加一个布尔值来只运行一次你的代码。

Try this, add your code on the start_count... then make sure to add a boolean to run your code only once.

$(function() {
    var oTop = $('#counter').offset().top - window.innerHeight;
    $(window).scroll(function(){

        var pTop = $('body').scrollTop();
        console.log( pTop + ' - ' + oTop );   //just for your debugging
        if( pTop > oTop ){
            start_count();
        }
    });
});

function start_count(){
    alert('start_count');
    //Add your code here
}

这篇关于当我滚动到特定&lt; div&gt;时,开始执行jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆