Как повернуть круговую диаграмму плагином progressbar против часовой стрелки?

#javascript #jquery #html #css #jquery-plugins

#javascript #jquery #HTML #css #jquery-плагины

Вопрос:

Я использую плагин с открытым исходным кодом в github, вот ссылка:https://github.com/yxfanxiao/jQuery-plugin-progressbar

Пожалуйста, ознакомьтесь с приведенными ниже кодами:

HTML:

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Progress Bar</title>
    <link rel="stylesheet" href="jQuery-plugin-progressbar.css">
    <script src="jquery-1.11.3.js"></script>
    <script src="jQuery-plugin-progressbar.js"></script>
</head>
<body>
    <div class="progress-bar position"></div>
    <div class="progress-bar position" data-percent="60" data-duration="1000" data-color="#ccc,yellow"></div>
    <div class="progress-bar position" data-percent="20" data-color="#a456b1,#12b321"></div>
    <input type="submit" value="加载">
    <script>
        $(".progress-bar").loading();
        $('input').on('click', function () {
             $(".progress-bar").loading();
        });
    </script>
</body>
</html>
  

JS:

 ;
(function ($) {
    $.fn.loading = function () {
        var DEFAULTS = {
            backgroundColor: '#b3cef6',
            progressColor: '#4b86db',
            percent: 75,
            duration: 2000
        };  

        $(this).each(function () {
            var $target  = $(this);

            var opts = {
            backgroundColor: $target.data('color') ? $target.data('color').split(',')[0] : DEFAULTS.backgroundColor,
            progressColor: $target.data('color') ? $target.data('color').split(',')[1] : DEFAULTS.progressColor,
            percent: $target.data('percent') ? $target.data('percent') : DEFAULTS.percent,
            duration: $target.data('duration') ? $target.data('duration') : DEFAULTS.duration
            };
            // console.log(opts);

            $target.append('<div class="background"></div><div class="rotate"></div><div class="left"></div><div class="right"></div><div class=""><span>'   opts.percent   '%</span></div>');

            $target.find('.background').css('background-color', opts.backgroundColor);
            $target.find('.left').css('background-color', opts.backgroundColor);
            $target.find('.rotate').css('background-color', opts.progressColor);
            $target.find('.right').css('background-color', opts.progressColor);

            var $rotate = $target.find('.rotate');
            setTimeout(function () {    
                $rotate.css({
                    'transition': 'transform '   opts.duration   'ms linear',
                    'transform': 'rotate('   opts.percent * 3.6   'deg)'
                });
            },1);       

            if (opts.percent > 50) {
                var animationRight = 'toggle '   (opts.duration / opts.percent * 50)   'ms step-end';
                var animationLeft = 'toggle '   (opts.duration / opts.percent * 50)   'ms step-start';  
                $target.find('.right').css({
                    animation: animationRight,
                    opacity: 1
                });
                $target.find('.left').css({
                    animation: animationLeft,
                    opacity: 0
                });
            } 
        });
    }
})(jQuery);
  

CSS:

 .position {
  float: left;
  margin: 100px 50px;
}

.progress-bar {
  position: relative;
  height: 100px;
  width: 100px;
}
.progress-bar div {
  position: absolute;
  height: 100px;
  width: 100px;
  border-radius: 50%;
}
.progress-bar div span {
  position: absolute;
  font-family: Arial;
  font-size: 25px;
  line-height: 75px;
  height: 75px;
  width: 75px;
  left: 12.5px;
  top: 12.5px;
  text-align: center;
  border-radius: 50%;
  background-color: white;
}
.progress-bar .background {
  background-color: #b3cef6;
}
.progress-bar .rotate {
  clip: rect(0 50px 100px 0);
  background-color: #4b86db;
}
.progress-bar .left {
  clip: rect(0 50px 100px 0);
  opacity: 1;
  background-color: #b3cef6;
}
.progress-bar .right {
  clip: rect(0 50px 100px 0);
  transform: rotate(180deg);
  opacity: 0;
  background-color: #4b86db;
}

@keyframes toggle {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
  

Обратите внимание, что вы можете загрузить zip-файл по предоставленной ссылке, содержащий эти коды. Как видно, изначально круговые диаграммы вращались по часовой стрелке. Все, что мне нужно, это заставить их вращаться против часовой стрелки. Это выглядело просто, но, к сожалению, я не мог справиться с этим в течение нескольких часов. Любая помощь или совет были бы очень признательны! Спасибо!!

Редактировать: Пожалуйста, обратите внимание, что начальная точка (origin) анимации не должна изменяться, должна начинаться сверху (север).

Ответ №1:

Вы должны начать с умножения вашего значения поворота на его значение минус; -3.6 вместо 3.6 . Вам также придется соответствующим образом обновить CSS, поскольку в противном случае анимация начнется снизу, в отличие от оригинальной версии, где она начинается сверху. Вы можете обмануть это, поменяв местами левый и правый компоненты, но это повлияет на значения прогресса менее чем на 50%, поэтому вам следует добавить оператор else, чтобы справиться и с этим. Следовательно, конечный файл JS становится таким, как показано ниже;

JS:

 ;
(function ($) {
    $.fn.loading = function () {
        var DEFAULTS = {
            backgroundColor: '#f00',
            progressColor: '#adadad',
            percent: 75,
            duration: 2000
        };  

        $(this).each(function () {
            var $target  = $(this);

            var opts = {
            backgroundColor: $target.data('color') ? $target.data('color').split(',')[0] : DEFAULTS.backgroundColor,
            progressColor: $target.data('color') ? $target.data('color').split(',')[1] : DEFAULTS.progressColor,
            percent: $target.data('percent') ? $target.data('percent') : DEFAULTS.percent,
            duration: $target.data('duration') ? $target.data('duration') : DEFAULTS.duration
            };

            $target.append('<div class="background"></div><div class="rotate"></div>' 
                '<div class="left"></div>' 
                '<div class="right"></div><div class=""><span>'  
                  opts.percent   '%</span></div>');

            $target.find('.background').css('background-color', opts.backgroundColor);
            $target.find('.left').css('background-color', opts.backgroundColor);
            $target.find('.rotate').css('background-color', opts.progressColor);
            $target.find('.right').css('background-color', opts.progressColor);

            var $rotate = $target.find('.rotate');
            setTimeout(function () {    
                $rotate.css({
                    'transition': 'transform '   opts.duration   'ms linear',
                    'transform': 'rotateZ('   -opts.percent * 3.6   'deg)'
                });
            },1);       

            if (opts.percent > 50) {
                var animationRight = 'toggle '   (opts.duration / opts.percent * 50)   'ms step-end';
                var animationLeft = 'toggle '   (opts.duration / opts.percent * 50)   'ms step-start';  
                $target.find('.left').css({
                    animation: animationRight,
                    opacity: 1
                });
                $target.find('.right').css({
                    animation: animationLeft,
                    opacity: 0
                });
            } 
            else {
                var animationRight = 'toggle '   (opts.duration / opts.percent * 50)   'ms step-end';
                var animationLeft = 'toggle '   (opts.duration / opts.percent * 50)   'ms step-start';  
                $target.find('.left').css({
                    animation: animationRight,
                    opacity: 0
                });
                $target.find('.right').css({
                    animation: animationLeft,
                    opacity: 1
                });
            }
        });
    }
})(jQuery);
  

Комментарии:

1. Изменение влево / вправо — отличная идея! Я все время играл с css. Спасибо.