javascript - 如何在窗口滚动时将数字递增 1

标签 javascript jquery css 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 + '%');
 }
})

最佳答案

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

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

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>

关于javascript - 如何在窗口滚动时将数字递增 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42354375/

相关文章:

JQuery 在重定向之前检查哪个输入文本框的边框颜色是红色

php - CSS 无法从 php 的相对路径工作 'includes'

javascript - 加载 db.json 时出错

javascript - 如何显示 ajax 数据库查询的结果?

javascript - 如何在 Compromise.js 中匹配任何时态的动词

javascript - javascript函数中的数据切换

html - 我应该如何在 CSS 中拆分网格?

php - 为什么使用 CSS 无法正确显示图像?

javascript - 使用 browserify 无法找到 Breeze 模块

javascript - 如何在幻灯片切换中先隐藏div并在单击时显示?