当元素在视图中时运行脚本

时间:2016-12-14 18:36:47

标签: javascript scroll

有人可以修复此脚本,以便在元素位于视图中时运行。换句话说,它需要等到它可见才能运行。谢谢! -Dan

$('.amount-chart').each(function(){
var $chart = $(this),
  size = parseFloat( $chart.outerWidth() ),
  clearSet;

$chart.css({
  height: size
})
.easyPieChart({
    size: size,
    animate: 2000,
            onStep: function(from, to, currentValue) {
                $(this.el).find('span.amount-counter').text(Math.round(currentValue));
            }
});

$(window).on('resize', function(){

   size = parseFloat( $chart.outerWidth() );

   $chart.css({
      height: size
   });

   //clearTimeout(clearSet);
   //clearSet = setTimeout(function(){
      $chart.removeData('easyPieChart').find('canvas').remove();
      $chart.easyPieChart({
         size: size,
         animate: 1
      });
   //}, 100);
});    

});

1 个答案:

答案 0 :(得分:3)

感谢您的完整描述! 看demo

<强> HTML

<div id="el">Pie Chart</div>    

<强>的JavaScript

var inited = false
function init() {
   // init your chart
   // code here run once on element with id="el" will in viewport
}

$(window).on('scroll', function() {
  if ( inited ) {
    return
  }

  if ( el.offsetTop >= window.innerHeight + document.body.scrollTop ) {
    inited = true
    init()
  }
})