如何在窗口滚动上增加一个数字1

Tay*_*ter 3 javascript css jquery events scroll

我有一种固定在我页面侧面的进度跟踪器,当你滚动时,我希望线条在用户向下滚动页面时获得高度(以百分比表示).当用户滚动时,我无法将高度增加一个.这是我目前的代码.

JS

$(window).scroll(function(){
 var number = 0; /* I'd like to increment this by one on scroll */
 // Only start the process when the first section comes into view
 if($("#progress-tracker-nav li").hasClass('active-section')) {
  number++; /* I'd like to increment this by one on scroll */
  $(".progress-line").css('height', number + '%');
 }
})
Run Code Online (Sandbox Code Playgroud)

Mih*_*nut 5

您必须numberscroll事件处理程序之外声明变量,因为每次scroll触发事件时,变量值都是refreshed.

在当前代码中,0number变量分配每个时间值.

var number = 0;
$(window).scroll(function(){ 
  number++;
  $("#number").text(number + '%');
})
Run Code Online (Sandbox Code Playgroud)
body{
  height:1000px;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="number"></div>
Run Code Online (Sandbox Code Playgroud)