滚动触发甜甜圈图动画

时间:2020-02-26 20:03:28

标签: javascript jquery html css

我用简单的填充动画创建了一些甜甜圈图,但是在滚动触发动画时遇到了麻烦。添加animate.css和wow.js是一个好主意,还是有一种更简单的方法来触发函数内部的动画?如果您能解决此问题,请先谢谢您的帮助。

<div class="donut-chart orange" data-percent="72">
  <p><span class="counter" data-count="72">0</span>%</p>
  <div class="doughnut"></div>
</div>
$(function() {
  $('.donut-chart').each(function(index) {
    $(this).append('<svg preserveAspectRatio="xMidYMid" xmlns:xlink="http://www.w3.org/1999/xlink" id="donutChartSVG' + index + '"><path d="M100,100"/></svg>');
    var p = new Donut_chart({
      element: $('#donutChartSVG' + index),
      percent: $(this).attr('data-percent')
    });
    p.animate();
  });
});

$('.counter').each(function() {
  var $this = $(this),
    countTo = $this.attr('data-count');

  $({
    countNum: $this.text()
  }).animate({
    countNum: countTo
  }, {
    duration: 2000,
    easing: 'linear',
    step: function() {
      $this.text(Math.floor(this.countNum));
    },
    complete: function() {
      $this.text(this.countNum);
    }
  });
});
.donut-chart svg {
  pointer-events: none;
  height: 100%;
  stroke: #19a8ff;
}

.donut-chart svg path {
  fill: none;
  stroke-width: 35px;
  stroke: #19a8ff;
}

.donut-chart {
  width: 200px;
  height: 200px;
  display: inline-block;
  left: 20%;
  margin-bottom: 30px;
}

.donut-chart p {
  margin: 0;
  position: absolute;
  left: 1%;
  top: 25%;
  font-family: 'Open Sans', sans-serif;
  font-weight: bolder;
  color: #222;
  width: 100%;
  text-align: center;
  font-size: 2em;
}

.doughnut {
  border: 35px solid #EAECEF;
  border-radius: 100px;
  height: 200px;
  width: 200px;
  position: absolute;
  top: 0px;
  z-index: -1;
}

1 个答案:

答案 0 :(得分:0)

尝试此操作,只需检查用户滚动条是否包含在事件函数if()中即可。

$(window).scroll(function() {
    if ($('.donut-chart').is(':visible')) {
        // do your stuff here, include function with p.animate();
    }
});

,但请记住,这可能会降低网站的性能。您可以访问此网站进行改进,https://johnresig.com/blog/learning-from-twitter/