jQuery - 滚动时增加计数器的值

时间:2018-03-27 14:31:38

标签: javascript jquery

我正在建立一个用户滚动并且分数增加的系统。有一个计数器,我想在滚动时增加使用jQuery的值(这样页面不需要刷新)。

我该怎么做?

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
jQuery(function() {
    jQuery(window).scroll(function(){
        if(jQuery(this).scrollTop() > 2000) {
            // ......
        }
    }); 
}); 
</script>

它应该每增加2000px。

2 个答案:

答案 0 :(得分:1)

这不是真正的反击,您只需将scrollTop除以2000即可获得价值。

jQuery(function($) {
    $(window).on('scroll', function() {
        var count = Math.floor($(this).scrollTop() / 2000);
        $('#counter').text(count);
    });
});
#counter {
  position: fixed;
}

#content {
  width: 10px;
  height: 20000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter">0</div>
<div id="content"></div>

如果你想保持最高金额,只需增加,但不要减少。您可以简单地使用辅助变量,在我的示例中称为highscore

jQuery(function($) {
    var highscore = 0;

    $(window).on('scroll', function() {
        var count = Math.floor($(this).scrollTop() / 2000);

        if(count > highscore) {
            $('#counter').text(highscore = count);
        }
    });
});
#counter {
  position: fixed;
}

#content {
  width: 10px;
  height: 20000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter">0</div>
<div id="content"></div>

答案 1 :(得分:0)

var counter = 0;
jQuery(function() {
    var nextIncrmenet = 2000;
    jQuery(window).scroll(function(){
        if(jQuery(this).scrollTop() > nextIncrmenet) {
            counter = counter + 1;
            nextIncrmenet = nextIncrmenet + 2000;
        }
    }); 
});