js как поменять цвет цифр в числе если первые ноли 000
Подскажите как поменять первые цифры нолей в числе
То есть, число 00012500 Нужно поменять цвет первых нолей, но число может меняться, может быть такое, что первые цифры будет один ноль или вовсе без ноля
Вот мой пример, тут конечно уже готовый счетчик, но не знаю как сделать так, что бы первые ноли были на пример красного цвета
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals).padStart(8,0));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
jQuery(function($) {
let maxamount = $('.counter1').data('counter')
let qwe = maxamount.toString();
let abc = qwe[1];
console.log(abc)
if (Number(qwe) > 0) {
// el.style.color = 'red'
console.log('red')
// document.getElementById('counter1').className += ' myclass'
// $('#counter1').addClass('myclass');
} else {
// el.style.color = 'blue'
console.log('blue')
}
$('.counter1').countTo({
from: 1,
to: $('.counter1').data('counter'),
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="counter1" id="counter1" data-counter="12500"></span>
Ответы (1 шт):
Автор решения: UModeL
→ Ссылка
Модифицируйте функцию, добавив метод replace() при выводе, и оборачивайте ведущие нули в <span> с определённым CSS-классом. Ну, а в стилях задавайте этому классу желаемый вид:
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
// После формирования конечного значения, ищём нули и оборачиваем их в <span> с нужным классом
$(_this).html(value.toFixed(options.decimals).padStart(8, 0).replace(/^(0+)/, `<span class="lead-zero">$1</span>`));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
$('.counter1').countTo({
from: 1,
to: $('.counter1').data('counter'),
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
/* Можно стилизовать как угодно, но нужно помнить,
что при каждой итерации счётчика, добавление тега
с классом происходит заново, поэтому нельзя добавить,
например, анимацию с @keyframes или transition */
.lead-zero { color: red; font: bold 20px sans-serif; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="counter1" id="counter1" data-counter="12500"></span>