【问题标题】:How to trigger CSS animation on View/Scroll?如何在 View/Scroll 上触发 CSS 动画?
【发布时间】:2021-12-11 11:34:04
【问题描述】:

我有一个动画折线图的简单代码。动画效果很好,但它在页面加载时开始。我希望它在该部分位于查看器屏幕中/查看器滚动到页面的该部分时启动。

如果它需要像 JS 这样的其他代码。请告诉我。谢谢!

这里是 HTML 和 CSS 代码。这是Codepen demo

HTML:

  <div class="wrapper">
    <h3>Papua New Guinea</h3>
    <br>
    <p>Papua New Guinea is one of the most culturally diverse countries in the world.
      As of 2019, it is also the most rural, as only 13.25% of its people live in urban centres.
      Most of the
      population of more than 8,000,000 people live in customary communities, which are as diverse
      as the languages.</p>
    <h5>Living in Urban communities</h5>
    <div class="line line1">13.25%</div>
    <h5>Living in Customary Communities</h5>
    <div class="line line2">86.75</div>
  </div>

CSS:

.wrapper {
  width: 800px;
  margin: 0 auto;
}

.wrapper h3 {
  text-align: center;
  text-transform: uppercase;
  margin-top: 40px;
}

.wrapper h5 {
  text-align: left;
}

.line {
  height: 25px;
  min-width: 800px;
  margin: 0 auto 10px;
  line-height: 25px;
  font-size: 14px;
  color: #fff;
  padding: 0 0 0 10px;
  position: relative;
}

.line:before {
  content: "";
  width: 100%;
  position: absolute;
  left: 0;
  height: 25px;
  top: 0;
  z-index: -2;
  background: #d2d6d7;
}

.line:after {
  content: "";
  background: #333;
  height: 25px;
  transition: 0, 8s;
  display: block;
  width: 100%;
  animation: animate 1 4s;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
}

.line1:after {
  max-width: 13.25%;
}

.line2:after {
  max-width: 86.75%;
}

@keyframes animate {
  0% {
    width: 0;
  }
  100% {
    width: 100%;
  }
}

【问题讨论】:

  • 是的,你需要一些 JS。调查 IntersectionObserver,它会告诉您要设置动画的位何时进入视口。另外,也许您可​​以将 javascript 标签添加到您的问题中。

标签: html css css-animations


【解决方案1】:

您可以使用动画延迟,但这对您没有帮助。您可以使用 JS 代码并跟踪事件。这是代码示例:

var $win = $(window);
var $marker = $('#marker');
$win.scroll(function() {
    if ($win.scrollTop() + $win.height() >= $marker.offset().top) {
        $win.unbind('scroll');
        // load there
    }
});

【讨论】:

  • js文件如何使用?我只是粘贴它吗?
  • 您必须将其添加到您的网站代码中,可以使用单独的 .js 文件,也可以使用 &lt;script&gt; 标记直接在 HTML 代码中。
猜你喜欢
  • 1970-01-01
  • 2019-01-03
  • 2020-07-24
  • 2020-11-26
  • 1970-01-01
  • 2017-12-04
  • 1970-01-01
  • 2018-07-28
相关资源
最近更新 更多