首页 > 解决方案 > 如何延迟 html/css 加载直到项目在视口中

问题描述

我在图表上有一个动画,但我希望 CSS 动画在它进入用户视口后加载。目前它在页面加载时加载,但这意味着一旦用户滚动到该部分,动画就已经发生了。

HTML & CSS 如下所示:

.chart[data-percent='100'] .outer {
  stroke-dashoffset: 0;
  -webkit-animation: show100 2s;
  animation: show100 2s;
}

.chart[data-percent='96'] .outer {
  stroke-dashoffset: 22;
  -webkit-animation: show96 2s;
  animation: show96 2s;
}

.chart[data-percent='77'] .outer {
  stroke-dashoffset: 123;
  -webkit-animation: show75 2s;
  animation: show75 2s;
}

.chart[data-percent='75'] .outer {
  stroke-dashoffset: 133;
  -webkit-animation: show75 2s;
  animation: show75 2s;
}

.chart[data-percent='52'] .outer {
  stroke-dashoffset: 257;
  -webkit-animation: show52 2s;
  animation: show52 2s;
}

.chart[data-percent='50'] .outer {
  stroke-dashoffset: 267;
  -webkit-animation: show50 2s;
  animation: show50 2s;
}

.chart[data-percent='25'] .outer {
  stroke-dashoffset: 401;
  -webkit-animation: show25 2s;
  animation: show25 2s;
}

@-webkit-keyframes show100 {
  from {
    stroke-dashoffset: 537;
  }
  to {
    stroke-dashoffset: 0;
  }
}

@keyframes show96 {
  from {
    stroke-dashoffset: 537;
  }
  to {
    stroke-dashoffset: 22;
  }
}

@keyframes show75 {
  from {
    stroke-dashoffset: 537;
  }
  to {
    stroke-dashoffset: 124;
  }
}

@-webkit-keyframes show52 {
  from {
    stroke-dashoffset: 537;
  }
  to {
    stroke-dashoffset: 257;
  }
}

@-webkit-keyframes show50 {
  from {
    stroke-dashoffset: 537;
  }
  to {
    stroke-dashoffset: 267;
  }
}

@keyframes show25 {
  from {
    stroke-dashoffset: 537;
  }
  to {
    stroke-dashoffset: 401;
  }
}
<div class="row stat-wheel">
  <div class="col-sm-4">
    <p class="stat-figure">52%</p>
    <figure class="chart" data-percent="52">
      <svg width="200" height="200">
        <circle class="outer" cx="95" cy="95" r="85" transform="rotate(-90, 95, 95)"/>
      </svg>
    </figure>
    <p class="white center">increase in sales generated through campaigns</p>
  </div>
  <div class="col-sm-4">
    <p class="stat-figure">77%</p>
    <figure class="chart" data-percent="77">
      <svg width="200" height="200">
        <circle class="outer" cx="95" cy="95" r="85" transform="rotate(-90, 95, 95)"/>
      </svg>
    </figure>
    <p class="white center">return on investment in the first 2 months</p>
  </div>
  <div class="col-sm-4">
    <p class="stat-figure">96%</p>
    <figure class="chart" data-percent="96">
      <svg width="200" height="200">
        <circle class="outer" cx="95" cy="95" r="85" transform="rotate(-90, 95, 95)"/>
      </svg>
    </figure>
    <p class="white center">increase in the quality of sales leads generated</p>
  </div>
</div>

标签: javascripthtmlcssloadviewport

解决方案


您可以检查交叉点观察者 api,它会告诉您元素何时在您的视口中可见。你可以听它,然后开始你的动画。


推荐阅读