CSS / jQuery: динамически обновляемый текст отображается справа, а не внутри круглого индикатора выполнения - PullRequest
1 голос
/ 11 июля 2020

Я пытаюсь реализовать круговой индикатор выполнения с анимацией и наткнулся на плагин из ресурса ниже.

Я загрузил и включил плагин и использовал исходный код (HTML и JS) с демонстрационной страницы, и с этим он работает. Однако моя проблема в том, что анимированные тексты, то есть значения, которые генерируются через JS (от 0 до установленного процента) , появляются прямо из кругов / диаграмм, а не внутри них (как в демонстрации).

Я предполагаю, что мне не хватает CSS здесь , но я не уверен, что мне нужно добавить, чтобы переместить значения внутри кругов / диаграмм . В CSS из исходного кода есть комментарий, говорящий, что он здесь не требуется. Может ли кто-нибудь помочь мне с этим?

Ссылки:

HTML:

<h1 style="margin-top:150px;">jQuery Circle Progress Demos</h1>
<div class="circles">
    <div class="first_circle">
        <span>no <br/> animation</span>
    </div>
    <div class="second_circle">
        <strong>0</strong>  <!-- This should appear inside the circle when being updated via JS -->
        <span>animation <br/> progress</span>
    </div>
    <div class="third_circle">
        <strong>0</strong>  <!-- This should appear inside the circle when being updated via JS -->
        <span>value <br/> progress</span>
    </div>
    <div class="forth_circle">
        <span>solid fill, <br/> custom angle</span>
    </div>
    <div class="fifth_circle">
        <span>image fill, <br/> custom sizes</span>
    </div>
</div>

JS:

$(document).ready(function() {  
    $('.first_circle').circleProgress({
        value: 0.35,
        animation: false,
        fill: { gradient: ['#ff1e41', '#ff5f43'] }
    });
    $('.second_circle').circleProgress({
        value: 0.6
    }).on('circle-animation-progress', function(event, progress) {
        $(this).find('strong').html(parseInt(100 * progress) + '<i>%</i>');
    });
    $('.third_circle').circleProgress({
        value: 0.8,
        fill: { gradient: ['#0681c4', '#07c6c1'] }
    }).on('circle-animation-progress', function(event, progress, stepValue) {
        $(this).find('strong').text(String(stepValue.toFixed(2)).substr(1));
    });
    $('.forth_circle').circleProgress({
        startAngle: -Math.PI / 4 * 3,
        value: .5,
        fill: { color: '#ffa500' }
    });
    $('.fifth_circle').circleProgress({
        value: 1,
        size: 60,
        thickness: 20,
        fill: {
            color: 'lime'
        }
    });
});

Заранее большое спасибо, Том

Ответы [ 2 ]

1 голос
/ 11 июля 2020

Две проблемы. Во-первых, вам не хватает некоторых CSS, чтобы демо работало. Демонстрация ссылается на файл page-styles.css, который содержит некоторые CSS для кругов. И здесь возникает вторая проблема. Даже если вы просто вставите CSS, он не будет работать «как есть», потому что circle должен быть отдельным классом. В вашей разметке и коде вы объединили два класса, добавив подчеркивание между first и circle:

<div class="first_circle">

Вместо:

<div class="first circle">

Итак, для вашего способа работы , вам нужно либо изменить CSS, либо просто разделить классы.

Вот пример с соответствующим CSS добавленным (я только что скопировал соответствующий CSS из файла page-styles.css , а не все):

$(document).ready(function() {
  $('.first.circle').circleProgress({
    value: 0.35,
    animation: false,
    fill: {
      gradient: ['#ff1e41', '#ff5f43']
    }
  });
  $('.second.circle').circleProgress({
    value: 0.6
  }).on('circle-animation-progress', function(event, progress) {
    $(this).find('strong').html(parseInt(100 * progress) + '<i>%</i>');
  });
  $('.third.circle').circleProgress({
    value: 0.8,
    fill: {
      gradient: ['#0681c4', '#07c6c1']
    }
  }).on('circle-animation-progress', function(event, progress, stepValue) {
    $(this).find('strong').text(String(stepValue.toFixed(2)).substr(1));
  });
  $('.forth.circle').circleProgress({
    startAngle: -Math.PI / 4 * 3,
    value: .5,
    fill: {
      color: '#ffa500'
    }
  });
  $('.fifth.circle').circleProgress({
    value: 1,
    size: 60,
    thickness: 20,
    fill: {
      color: 'lime'
    }
  });
});
.circle {
  width: 100px;
  margin: 6px 6px 20px;
  display: inline-block;
  position: relative;
  text-align: center;
  line-height: 1.2;
}

.circle canvas {
  vertical-align: top;
}

.circle strong {
  position: absolute;
  top: 30px;
  left: 0;
  width: 100%;
  text-align: center;
  line-height: 40px;
  font-size: 30px;
}

.circle strong i {
  font-style: normal;
  font-size: 0.6em;
  font-weight: normal;
}

.circle span {
  display: block;
  color: #aaa;
  margin-top: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://www.jqueryscript.net/demo/Animated-Circular-Progress-Bar-with-jQuery-Canvas-Circle-Progress/dist/circle-progress.js"></script>
<div class="circles">
  <div class="first circle">
    <span>no <br/> animation</span>
  </div>

  <div class="second circle">
    <strong></strong>
    <span>animation <br/> progress</span>
  </div>

  <div class="third circle">
    <strong></strong>
    <span>value <br/> progress</span>
  </div>

  <div class="forth circle">
    <span>solid fill, <br/> custom angle</span>
  </div>

  <div class="fifth circle">
    <span>image fill, <br/> custom sizes</span>
  </div>
</div>
1 голос
/ 11 июля 2020

/* Examples */
(function($) {
  /*
   * Example 1:
   *
   * - no animation
   * - custom gradient
   *
   * By the way - you may specify more than 2 colors for the gradient
   */
  $('.first.circle').circleProgress({
    value: 0.35,
    animation: false,
    fill: {gradient: ['#ff1e41', '#ff5f43']}
  });

  /*
   * Example 2:
   *
   * - default gradient
   * - listening to `circle-animation-progress` event and display the animation progress: from 0 to 100%
   */
  $('.second.circle').circleProgress({
    value: 0.6
  }).on('circle-animation-progress', function(event, progress) {
    $(this).find('strong').html(Math.round(100 * progress) + '<i>%</i>');
  });

  /*
   * Example 3:
   *
   * - very custom gradient
   * - listening to `circle-animation-progress` event and display the dynamic change of the value: from 0 to 0.8
   */
  $('.third.circle').circleProgress({
    value: 0.75,
    fill: {gradient: [['#0681c4', .5], ['#4ac5f8', .5]], gradientAngle: Math.PI / 4}
  }).on('circle-animation-progress', function(event, progress, stepValue) {
    $(this).find('strong').text(stepValue.toFixed(2).substr(1));
  });

  /*
   * Example 4:
   *
   * - solid color fill
   * - custom start angle
   * - custom line cap
   * - dynamic value set
   */
  var c4 = $('.forth.circle');

  c4.circleProgress({
    startAngle: -Math.PI / 4 * 3,
    value: 0.5,
    lineCap: 'round',
    fill: {color: '#ffa500'}
  });

  // Let's emulate dynamic value update
  setTimeout(function() { c4.circleProgress('value', 0.7); }, 1000);
  setTimeout(function() { c4.circleProgress('value', 1.0); }, 1100);
  setTimeout(function() { c4.circleProgress('value', 0.5); }, 2100);

  /*
   * Example 5:
   *
   * - image fill; image should be squared; it will be stretched to SxS size, where S - size of the widget
   * - fallback color fill (when image is not loaded)
   * - custom widget size (default is 100px)
   * - custom circle thickness (default is 1/14 of the size)
   * - reverse drawing mode
   * - custom animation start value
   * - usage of "data-" attributes
   */
  $('.fifth.circle').circleProgress({
    value: 0.7
    // all other config options were taken from "data-" attributes
    // options passed in config object have higher priority than "data-" attributes
    // "data-" attributes are taken into account only on init (not on update/redraw)
    // "data-fill" (and other object options) should be in valid JSON format
  });
})(jQuery);
body {
  background-color: #444;
  padding-top: 40px;
  font: 15px/1.3 Arial, sans-serif;
  color: #fff;
  text-align: center;
}

a {
  color: orange;
}

.new-tab-link {
  padding-right: 14px;
  background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3ggXDSIzCeRHfQAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAAA9SURBVBjTY2RAA/+XMvxHF2NkwAOwacCq4P9Shv8suFQzRiNsYUEXwKoJ2VhkNrIaJgYiAAs2N2BVRMirAD6JHi10MCdVAAAAAElFTkSuQmCC) no-repeat right center;
}

.page-title {
  font: 400 40px/1.5 Open Sans, sans-serif;
  text-align: center;
}

.circles {
  margin-bottom: -10px;
}

.circle {
  width: 100px;
  margin: 6px 6px 20px;
  display: inline-block;
  position: relative;
  text-align: center;
  line-height: 1.2;
}

.circle canvas {
  vertical-align: top;
}

.circle strong {
  position: absolute;
  top: 30px;
  left: 0;
  width: 100%;
  text-align: center;
  line-height: 40px;
  font-size: 30px;
}

.circle strong i {
  font-style: normal;
  font-size: 0.6em;
  font-weight: normal;
}

.circle span {
  display: block;
  color: #aaa;
  margin-top: 12px;
}

p {
  margin: 40px 0;
}
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="https://rawgit.com/kottenator/jquery-circle-progress/1.2.2/dist/circle-progress.js"></script>

<div class="circles">
    <div class="first circle">
      <span>no <br> animation</span>
    </div>

    <div class="second circle">
      <strong></strong>
      <span>animation <br> progress</span>
    </div>

    <div class="third circle">
      <strong></strong>
      <span>value <br> progress</span>
    </div>

    <div class="forth circle">
      <span>custom angle, <br> value update</span>
    </div>

    <div
      class="fifth circle"
      data-value="0.9"
      data-size="60"
      data-thickness="20"
      data-animation-start-value="1.0"
      data-fill="{
        &quot;color&quot;: &quot;rgba(0, 0, 0, .3)&quot;,
        &quot;image&quot;: &quot;http://i.imgur.com/pT0i89v.png&quot;
      }"
      data-reverse="true"
    >
      <span>image fill, <br> custom sizes</span>
    </div>
  </div>
  

Я просто собрал это из демонстрации, я думаю, вы что-то пропустили или что-то удалили, поскольку это выдавало ошибки.

...