如何使用 waypoints 在滚动时激活进度条?

How to activate progress bar on scroll using waypoints?

我想在滚动时激活我的进度条并为此使用 waypoints.js。但是它不起作用,进度条在我滚动之前是 'filled' 或(like in my current code)在滚动和页面加载时保持 'empty'。

html:

<div id="progress-bar-start" class="center-block progress-wrapper">
    <h4>UI/UX Design:</h4>
    <div class="progress">
        <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="max-width: 60%">
            <span class="title">60%</span>
        </div>
    </div>
</div>

css:

#skills {
  margin-top: 0px;
  margin-bottom: 50px;
  .skills-title::first-letter {
    font-size: 60px;
    color: pink;
  }
  .progress-wrapper {
    width: 50%;
    margin-top: 30px;
    .progress-bar {
      background-color: pink;
      width: 0;
      animation: progress 1.5s ease-in-out forwards;
      .title {
        opacity: 0;
        animation: show 0.35s forwards ease-in-out 0.5s;
      }
    }
    .progress {
      height: 40px;
    }
  }
  @keyframes show {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }
}

js:

$('#skills').waypoint(function(direction) {
    if (direction === 'down') {
        $('.progress-bar').addClass("show");
    } else {
        $('.progress-bar').removeClass("show");
    }
}, {
    offset: '50%'
});

这里有两点需要注意。

  • 首先,让我们从 Waypoint 的 offset 选项开始:默认情况下,当元素的顶部碰到 window 的顶部时,会触发一个 Waypoint。 offset 指定这些顶部位置之间的触发距离。 在您的示例中,请务必注意,#skills 部分位于 window 的顶部,这意味着使用 offset >= 0 它会在页面加载时立即触发,并且仅触发一次(使用'down'方向)。
  • 其次,为了显示进度条,您必须设置进度条的 width,而不是 visibility/display。此外,应通过 width 而不是 max-width 属性来设置宽度,因为 运行 和 css 动画需要这样做。

所以,解决方法如下:

HTML

<div class="progress">
    <!-- CHANGE style="max-width: 60%" TO data-score="60%" -->
    <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" data-score="60%"></div>
</div>

JS

$('#skills').waypoint(function(direction) {
    if (direction === 'down') {
        $('.progress-bar').width(function(){
            // this here refers to individual .progress-bar items
            return $(this).data('score');
        });
    } else {
        $('.progress-bar').width(0);
    }
}, { offset: '10%' });

SCSS

#skills {
  margin-top: 100px;
  /* …the rest is the same… */
}

工作示例也可在 Fiddle 上找到。

更新(回答评论):
如果您希望每次用户向下滚动时都出现动画,但同时不显示进度条的递减动画,您可以按如下方式更改代码:

$('#skills').waypoint(function(direction) {
    if (direction === 'down') {
        $('.progress-bar').width(function(){
            // this here refers to individual .progress-bar items
            return $(this).data('score');
        });
    }
}, { offset: '10%' });

$('#skills').waypoint(function(direction) {
    if (direction === 'up') {
        $('.progress-bar').width(0);
    }
}, { offset: '100vh' });

上面的代码仍然是 运行 减少动画,但如果不是 运行 在 iframe 中(如 Fiddle 中),它将不可见,因为它在#skills 超出了视口。 (在这种情况下,您也可以使用可见性 类。) 为了更好的展示功能,我在这个Fiddle version.

里也设置了margin-top: 100vh; on #skills