滚动触发图表动画

时间:2016-03-16 22:52:50

标签: javascript

我目前正在逐渐消失div中的div,但在其中一个部分中,我有一个动画的图表,但当页面加载时它会动画。当你在页面上滚动它时,我需要它做什么。这是我目前的js:

JS CODE

$(document).ready(function() {

    /* Every time the window is scrolled ... */
    $(window).scroll( function(){

        /* Check the location of each desired element */
        $('.hideme').each( function(i){

            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();

            /* If the object is completely visible in the window, fade it it */
            if( bottom_of_window > bottom_of_object ){

                $(this).animate({'opacity':'1'},500);

            }

        }); 

    });





Chart.defaults.global.animationEasing = 'easeInOutQuad',
Chart.defaults.global.responsive = true;
Chart.defaults.global.scaleOverride = true;
Chart.defaults.global.scaleShowLabels = false;
Chart.defaults.global.scaleSteps = 10;
Chart.defaults.global.scaleStepWidth = 10;
Chart.defaults.global.scaleStartValue = 0;
Chart.defaults.global.tooltipFontFamily = 'Open Sans';
Chart.defaults.global.tooltipFillColor = '#FFFFFF';
Chart.defaults.global.tooltipFontColor = '#6E6E6E';
Chart.defaults.global.tooltipCaretSize = 0;
Chart.defaults.global.maintainAspectRatio = true;

Chart.defaults.Line.scaleShowHorizontalLines = false;
Chart.defaults.Line.scaleShowHorizontalLines = false;
Chart.defaults.Line.scaleGridLineColor = '#fff';
Chart.defaults.Line.scaleLineColor = '#eee';

var chart = document.getElementById('chart').getContext('2d'),
  gradient = chart.createLinearGradient(0, 0, 0, 0);

var data = {
  labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June'],

  datasets: [{
    label: 'Custom Label Name',
    fillColor: gradient,
    strokeColor: '#41AAE3',
    pointColor: '#41AAE3',
    pointStrokeColor: 'rgba(220,220,220,1)',
    pointHighlightFill: '#fff',
    pointHighlightStroke: 'rgba(220,220,220,1)',
    data: [5, 12, 28, 37, 60, 100]
  }]
};

gradient.addColorStop(0, 'rgba(255, 0,0, 0.5)');
gradient.addColorStop(0.5, 'rgba(255, 0, 0, 0.25)');
gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');

var chart = new Chart(chart).Line(data);


});

1 个答案:

答案 0 :(得分:1)

将图表代码包装成函数

var chartIsShown = false;

// .....

function chartInit() {
    chartIsShown = true;
    // chart code here
}

比#34内的每个功能内部;如果是可见的" if添加另一个if

if(this.id==="chartCanvasContainer" && chartIsShown===false) { // Add this
    chartInit();
}
$(this).animate({'opacity':'1'},500); // before this.

其中id="chartCanvasContainer"是分配给hideme画布的#chart父级的ID:

<div class="hideme">Lorem ipsum</div>
<div class="hideme" id="chartCanvasContainer"> <!-- assign the ID! -->
    <canvas id="chart"></canvas>
</div>
<div class="hideme">foo bar ofc</div>
<!-- .etc. -->