如何为页面上的圆形进度栏设置动画

时间:2019-05-18 04:43:15

标签: javascript jquery

我有一个圆形的进度条,可以在页面加载时进行动画处理,但是我希望它在用户向下滚动到页面时进行动画处理,因为它将位于页面中间。现在,如果页面加载,用户将看不到动画。

因此,从本质上讲,应该暂停动画,直到用户向下滚动到某个点为止,一旦看到该条,动画就开始播放。

我使用了这个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

1 个答案:

答案 0 :(得分:0)

Dan的结帐答案 关于Dan的回答,我添加了可用于启动/停止圆形进度条动画的代码

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);