仅当您在特定 div 的视图上滚动时才激活 CSS 动画

Active CSS animation only when you scroll on the view of the specific div

我在 CSS 和 HTML 中制作了一张图表,在这张图表中有一个图表加载动画。我只想在滚动包含图表的 div 视图时启动此动画。

我只想在页面上显示图表时才收费,我知道我必须使用javascript但是我是JS的初学者所以我不知道是否可以做类似的事情。

这是图表的fiddle:

https://jsfiddle.net/matteous1/pdL0kbqk/

HTML

<ul class="chart">
  <li>
    <span style="height:5%; background: rgba(0, 102, 255, 0.80);" title="ActionScript"></span>
  </li>
  <li>
    <span style="height:70%; background: rgba(204, 51, 51, 0.80);" title="JavaScript"></span>
  </li>
  <li>
    <span style="height:50%; background: rgba(255, 186, 2, 0.80);" title="CoffeScript"></span>
  </li>
  <li>
    <span style="height:75%; background: rgba(0, 153, 102, 0.80);" title="HTML"></span>
  </li>
  <li>
    <span style="height:90%; background: rgba(0, 102, 255, 0.80);" title="HTML"></span>
  </li>
  <li>
    <span style="height:15%; background: rgba(204, 51, 51, 0.80);" title="HTML"></span>
  </li>
  <li>
    <span style="height:40%; background: rgba(255, 186, 2, 0.80);" title="HTML"></span>
  </li>
  <li>
    <span style="height:55%; background: rgba(0, 153, 102, 0.80);" title="HTML"></span>
  </li>
</ul>   

CSS

.chart {
  display: table;
  table-layout: fixed;
  width: 90%;
  /*max-width: 700px;*/
  height: 65%;
  margin: 0 auto;
  background-image: linear-gradient(to top, rgba(0, 0, 0, 0.1) 2%, rgba(0, 0, 0, 0) 2%);
  background-size: 100% 50px;
  background-position: left top;
}
.chart li {
  position: relative;
  display: table-cell;
  vertical-align: bottom;
  height: 200px;
}
.chart span {
  margin: 0 1em;
  display: block;
  /*background: rgba(209, 236, 250, 0.75);*/
  animation: draw 1s ease-in-out;
}
.chart span:before {
  position: absolute;
  left: 0;
  right: 0;
  top: 100%;
  padding: 5px 1em 0;
  display: block;
  text-align: center;
  content: attr(title);
  word-wrap: break-word;
}

@keyframes draw {
  0% {
    height: 0;
  }
}

您可以使用 onscroll 事件并检查元素是否在视口中

 document.addEventListener('DOMContentLoaded', function() {
    var charElem = document.querySelector('.chart');

    var isVisible = false;
    window.onscroll = function() {
      if(isElementInViewport(charElem) && !isVisible) {
        charElem.className += " anim";
        isVisible = true;
      }
    }

    function isElementInViewport (el) {

        //special bonus for those using jQuery
        if (typeof jQuery === "function" && el instanceof jQuery) {
            el = el[0];
        }

        var rect = el.getBoundingClientRect();

        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
            rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
        );
    }
    });

https://jsfiddle.net/karthick6891/pdL0kbqk/1/

注:viewport 代码中的元素参考自此 link How to tell if a DOM element is visible in the current viewport?