如何在窗口滚动上增加一个数字1
我有一种固定在页面侧面的进度跟踪器,当你滚动时,我希望线条在用户向下滚动页面时获得高度(以百分比表示)。 当用户滚动时,我无法将高度增加一个。 这是我目前的代码。
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
变量值。
在当前代码中,每次为number
变量分配0
值。
var number = 0; $(window).scroll(function(){ number++; $("#number").text(number + '%'); })
body{ height:1000px; }
问题是你在scroll事件中定义number
。 您需要在外部定义它以便增加金额。
var number = 0; $(window).scroll(function(){ number++; });
您当前的这种方式意味着每次事件触发时number
都会重置为0。
要向下滚动增加数量,您可以这样做
var lastScrollPosition = $(document).scrollTop(); var number = 0; $(window).on('scroll', function(e) { if($(document).scrollTop() > lastScrollPosition ){ number++; } })
同样,如果您需要在用户向上滚动时减少数量,则可以将>
替换为<
。
如果要在向上滚动时降低高度并在向下滚动时增加高度,也可以执行此操作。
var lastScrollPosition = $(document).scrollTop(); var initalHeight = 100; $(window).on('scroll', function(e) { $(".progress-line").css('height', ((100/ (100 - $(document).scrollTop()/$(document).height()) + '%'); })
这些事件会非常频繁地触发,因此您可能希望将选择器移动到闭包中,这样就不必每次都重新计算它们:
function registerScrollEvent() { // get reference to DOM elements once since the scroll event fires frequently var number = 0, elNav = $("#progress-tracker-nav li"), elProgress = $(".progress-line"); $(window).scroll(function(){ // Only start the process when the first section comes into view if(elNav.hasClass('active-section')) { number++; elProgress.css('height', number + '%'); } }) }
此外,请注意与滚动事件相关的IOS问题仅在滚动完成后触发:
https://github.com/twbs/bootstrap/issues/16202
此外,不确定您计划如何重置。 无论是向上还是向下滚动,滚动事件都将触发,因此数字将继续增加。 那是你要的吗?
我认为进度条的高度应该相对于窗口的scrollTop
除以可能的最大滚动(文档的高度减去窗口的高度)。 使用这个公式:
percentage_of_height_of_progress_bar = 100 * scroll_top_of_window / (height_of_document - height_of_window);
例:
$(window).scroll(function() { var percent = $(document).scrollTop() / ($(document).height() - $(window).height()) * 100; $(".progress").css('width', percent + '%'); })
body { height: 1000px; } .progress { position: fixed; width: 0%; height: 10px; background: red; }