Дорабатываем визуализатор желаний
После долгого перерыва продолжил работать с визуализатором прогресса желаний. Теперь работают кнопки плюс и минус. Актуальный код
<div class="wrap_range" translate="no">
<!-- Контейнер для кнопок и шкалы -->
<div class="controls-container">
<button id="btn-minus" class="ctrl-btn">-</button>
<div class="range" id="progress-range" style="--p:70">
<div class="range__label">Progress</div>
</div>
<button id="btn-plus" class="ctrl-btn">+</button>
</div>
<button id="add_dpv" class="btn btn-primary" style="margin-top: 20px;">Добавить новый визуализатор</button>
</div>
<style>
@import url('https://fonts.googleapis.com/css2?family=Orbitron&display=swap');
.wrap_range {
background-color: #212121;
display: flex;
flex-direction: column; /* Элементы друг под другом */
justify-content: center;
align-items: center;
height: 250px;
color: #ccc;
font-family: sans-serif;
font-size: 18px;
border-radius: 8px;
}
.controls-container {
display: flex;
align-items: center;
gap: 15px; /* Расстояние между кнопками и шкалой */
}
/* Стили для кнопок плюс/минус */
.ctrl-btn {
background-color: #444;
color: #F3E600;
border: 2px solid #F3E600;
width: 40px;
height: 40px;
font-family: 'Orbitron', monospace;
font-size: 24px;
font-weight: bold;
cursor: pointer;
border-radius: 5px;
transition: all 0.2s ease;
display: flex;
justify-content: center;
align-items: center;
user-select: none;
}
.ctrl-btn:hover {
background-color: #F3E600;
color: #212121;
box-shadow: 0 0 10px #F3E600;
}
.ctrl-btn:active {
transform: scale(0.95);
}
.range {
position: relative;
background-color: #333;
width: 300px;
height: 30px;
transform: skew(30deg);
font-family: 'Orbitron', monospace;
overflow: hidden; /* Чтобы фон не вылезал за границы при анимации */
border: 1px solid #555;
}
.range:before {
width: calc(var(--p) * 1%);
content: '';
position: absolute;
top: 0;
left: 0;
height: 100%;
background-color: #F3E600;
z-index: 0;
animation: load .5s forwards linear;
transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1); /* Плавное изменение ширины */
}
.range:after {
counter-reset: progress var(--p);
content: counter(progress) '%';
color: #000;
font-weight: bold;
position: absolute;
left: 5%;
top: 50%;
transform: translateY(-50%) skewX(-30deg);
z-index: 1;
pointer-events: none;
}
.range__label {
transform: skew(-30deg) translateY(-100%);
line-height: 1.5;
text-align: center;
margin-bottom: 5px;
text-transform: uppercase;
font-size: 14px;
letter-spacing: 1px;
}
.btn-primary {
color: #fff;
background-color: #007bff;
border-color: #007bff;
cursor: pointer;
}
.btn {
display: inline-block;
font-weight: 400;
text-align: center;
white-space: nowrap;
vertical-align: middle;
user-select: none;
border: 1px solid transparent;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
border-radius: .25rem;
transition: all 0.15s ease-in-out;
cursor: pointer;
}
.btn:hover {
background-color: #0056b3;
border-color: #004085;
}
@keyframes load {
from { width: 0; }
}
</style>
<script>
// Инициализация переменных
let currentProgress = 0; // Начальное значение
const rangeElement = document.getElementById('progress-range');
const step = 1; // Шаг изменения процента
// Функция обновления шкалы
function updateProgress() {
// Ограничиваем значения от 0 до 100
if (currentProgress < 0) currentProgress = 0;
if (currentProgress > 100) currentProgress = 100;
// Обновляем CSS переменную напрямую без перезагрузки
rangeElement.style.setProperty('--p', currentProgress);
console.log("Текущий прогресс:", currentProgress + "%");
}
// Обработчик кнопки Минус
document.getElementById('btn-minus').addEventListener('click', function() {
currentProgress -= step;
updateProgress();
});
// Обработчик кнопки Плюс
document.getElementById('btn-plus').addEventListener('click', function() {
currentProgress += step;
updateProgress();
});
// Установка начального значения при загрузке
updateProgress();
if (typeof jQuery !== 'undefined') {
jQuery('#add_dpv').click(function() {
const btn = jQuery(this);
const originalText = btn.text();
btn.text('Загрузка...').prop('disabled', true);
jQuery.post("ajax.php", {
"action": "add_dpv"
})
.done(function(data) {
try {
var obj = JSON.parse(data);
console.log(obj);
// Здесь можно добавить логику успешного добавления
alert("Визуализатор добавлен!");
} catch (e) {
console.error("Ошибка парсинга JSON", e);
}
})
.fail(function() {
alert("Ошибка соединения");
})
.always(function() {
btn.text(originalText).prop('disabled', false);
});
});
} else {
console.warn("jQuery не найден. Кнопка 'Добавить визуализатор' не будет работать.");
}
</script>
Автор этого материала - я - Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML - то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.
Программы на заказ
Отзывы
Контакты