如何在窗口滚动上将数字递增1 [英] How To Increment A Number By 1 On Window Scroll

查看:72
本文介绍了如何在窗口滚动上将数字递增1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种进度跟踪器,它固定在页面的侧面,在您滚动时,我希望该行在用户向下滚动页面时增加高度(以百分比为单位).当用户滚动时,我无法使高度仅增加一.这是我当前的代码.

I have a type of progress tracker sitting fixed on the side of my page and as you scroll, I want the line to gain height (in percentages) as the user scrolls down the page. I am having trouble getting the height to increase by just one as the user scrolls. Here is my current code.

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 + '%');
 }
})

推荐答案

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

You have to declare number variable outside of the scroll event handler, because every time when scroll event is fired, the variable value is refreshed.

在当前代码中,每次为number变量分配0值.

In your current code, you assign every time 0 value for number variable.

var number = 0;
$(window).scroll(function(){ 
  number++;
  $("#number").text(number + '%');
})

body{
  height:1000px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="number"></div>

这篇关于如何在窗口滚动上将数字递增1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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