首页 > 解决方案 > 如何在页面向下滚动时为圆形进度条设置动画

问题描述

我有一个圆形进度条,在页面加载时会产生动画,但我希望它在用户向下滚动到它时产生动画,因为它会在页面的中间。现在如果页面加载,用户看不到动画。

所以本质上,动画应该暂停,直到用户向下滚动到某个点,一旦看到栏,动画就会开始。

我使用了这个 jquery 插件https://www.jqueryscript.net/loading/jQuery-Plugin-SVG-Progress-Circle.html

function makesvg(percentage, inner_text = "") {
    var abs_percentage = Math.abs(percentage).toString();
    var percentage_str = percentage.toString();
    var classes = ""
    if (percentage < 0) {
        classes = "danger-stroke circle-chart__circle--negative";
    } else if (percentage > 0 && percentage <= 30) {
        classes = "warning-stroke";
    } else {
        classes = "success-stroke";
    }
    var svg = '<svg class="circle-chart" viewbox="0 0 33.83098862 33.83098862" 
    xmlns = "http://www.w3.org/2000/svg" > ' +
    '<circle class="circle-chart__background" cx="16.9" cy="16.9" r="15.9"  / >
    ' +
    '<circle class="circle-chart__circle ' + classes + '"' +
        'stroke-dasharray="' + abs_percentage + ',100"    cx="16.9" cy="16.9" 
    r = "15.9" / > ' +
    '<g class="circle-chart__info">' +
    '   <text style="color:#fff;" class="circle-chart__percent" x="17.9" 
    y = "15.5" > '+percentage_str+' % < /text>';
    if (inner_text) {
        svg += '<text class="circle-chart__subline" x="16.91549431" 
        y = "22" > '+inner_text+' < /text>'
    }
    svg += ' </g></svg>';
    return svg
}

(function($) {
    $.fn.circlechart = function() {
        this.each(function() {
            var percentage = $(this).data("percentage");
            var inner_text = $(this).text();
            var inner_text2 = $(this).text();
            $(this).html(makesvg(percentage, inner_text));
        });
        return this;
    };
});

$('.circlechart').circlechart(); // Initialization

标签: javascriptjquery

解决方案


丹的结帐答案参考 的答案,我正在添加可用于启动/停止循环进度条动画的代码

function onVisibilityChange(el, callback) {
    var old_visible;
    return function () {
        var visible = isElementInViewport(el);
        if (visible != old_visible) {
            old_visible = visible;
            if (typeof callback == 'function') {
                callback(visible);
            }
        }
    }
}
var percentage = 0;
var handler = onVisibilityChange(el, function(visiblity_status) {
    /* your code go here */
    if (visibility_status) {
     if (percentage == 0) {
       $('.circlechart').circlechart(); 
     } else {
        // Code to resume progress bar if there is any method defined for the plugin you are using.
     }

    } else {
        // Code to stop progress bar if there is any method to stop it.
    }
});


//jQuery
$(window).on('DOMContentLoaded load resize scroll', handler); 

推荐阅读