Продвинутый конвертер единиц
Переводите между единицами длины, веса, объема и других величин.
Исходный код доступен в конце страницы.
Популярные преобразования:
История конвертаций
Продвинутый конвертер единиц- это мощный инструмент для мгновенного перевода между популярными единицами измерения:
- Длина: метры ↔ футы, километры ↔ мили.
- Вес: килограммы ↔ фунты, граммы ↔ унции.
- Объем: литры ↔ галлоны, миллилитры ↔ пинты.
- Температура: Цельсий ↔ Фаренгейт ↔ Кельвин.
- Время: часы ↔ минуты ↔ секунды.
- Скорость: км/ч ↔ мили/час ↔ м/с.
Функционал
- Поддержка 6 категорий единиц в одном инструменте.
- Популярные конвертации в один клик (например, «Кг → Фунты»).
- История расчетов — чтобы не потерять результаты.
Исходный код продвинутого конвертера единиц:
HTML:
<div class="vifed-container"> <!-- Выбор категории --> <div class="vifed-category-selector"> <select id="vifed-category"> </select> </div> <!-- Блок конвертации --> <div class="vifed-converter"> <div class="vifed-unit-row"> </div> <div class="vifed-unit-row"> </div> <div class="vifed-input-row"> <input type="number" id="vifed-input-value" placeholder="Введите значение"> </div> <div class="vifed-result-row"> <input type="text" id="vifed-output-value" placeholder="Результат" readonly> </div> </div> <!-- Быстрые конвертации --> <div class="vifed-quick-conversions"> </div> <!-- История расчетов --> <div class="vifed-history"> </div> </div>
CSS:
/* Основные стили */ : root { --primary - color: #2c5364; --secondary-color: # 8 b7355; --hover - color: #3a7bd5; --bg-color: # f5f7fa; --card - bg: #ffffff; --error - color: #dc3545; --success - color: #28a745; } .vifed - container { max - width: 800 px; margin: 0 auto; background: var (--card - bg); padding: 25 px; border - radius: 10 px; box - shadow: 0 5 px 15 px rgba(0, 0, 0, 0.1); } h1 { color: var (--primary - color); text - align: center; margin - bottom: 15 px; font - size: 1.8 rem; } .vifed - description { text - align: center; margin - bottom: 25 px; color: #666; font-size: 1rem; } /* Выбор категории */ .vifed-category-selector { margin-bottom: 20px; } .vifed-category-selector select { width: 100%; padding: 12px 15px; font-size: 1rem; border: 1px solid # ddd; border - radius: 8 px; background - color: #fff; appearance: none; background - image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e"); background - repeat: no - repeat; background - position: right 10 px center; background - size: 15 px; } /* Блок конвертации */ .vifed - converter { display: flex; flex - direction: column; gap: 15 px; margin - bottom: 25 px; } .vifed - unit - row { display: flex; align - items: center; gap: 10 px; } .vifed - unit - row label { font - size: 1 rem; color: #555; min-width: 40px; } .vifed-unit-row select { flex: 1; padding: 12px 15px; font-size: 1rem; border: 1px solid # ddd; border - radius: 8 px; background - color: #fff; appearance: none; background - image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e"); background - repeat: no - repeat; background - position: right 10 px center; background - size: 15 px; } .vifed - input - row { display: flex; gap: 10 px; margin - top: 10 px; } .vifed - input - row input { flex: 1; padding: 12 px 15 px; font - size: 1 rem; border: 1 px solid# ddd; border - radius: 8 px; } .vifed - input - row button { padding: 0 20 px; border: none; border - radius: 8 px; font - size: 1 rem; cursor: pointer; transition: all 0.2 s; } #vifed - convert { background - color: var (--primary - color); color: white; } #vifed - convert: hover { background - color: var (--hover - color); } .vifed - result - row { display: flex; gap: 10 px; margin - top: 5 px; } .vifed - result - row input { flex: 1; padding: 12 px 15 px; font - size: 1 rem; border: 1 px solid# ddd; border - radius: 8 px; background - color: #f9f9f9; } #vifed - copy { background - color: var (--secondary - color); color: white; padding: 0 15 px; border: none; border - radius: 8 px; font - size: 1 rem; cursor: pointer; transition: all 0.2 s; } #vifed - copy: hover { background - color: #9d8260; } /* Быстрые конвертации */ .vifed-quick-conversions { margin-bottom: 25px; } .vifed-quick-conversions h3 { margin-bottom: 12px; font-size: 1.1rem; color: var(--primary-color); } .vifed-quick-buttons { display: flex; flex-wrap: wrap; gap: 8px; } .vifed-quick-buttons button { padding: 8px 12px; background-color: # e9ecef; border: none; border - radius: 6 px; font - size: 0.85 rem; cursor: pointer; transition: background - color 0.2 s; } .vifed - quick - buttons button: hover { background - color: #d1d7dc; } /* История расчетов */ .vifed - history { border - top: 1 px solid# eee; padding - top: 20 px; } .vifed - history h3 { margin - bottom: 12 px; font - size: 1.1 rem; color: var (--primary - color); } #vifed - history - list { list - style: none; margin - bottom: 15 px; } #vifed - history - list li { padding: 10 px 0; border - bottom: 1 px solid# f0f0f0; font - size: 0.9 rem; } #vifed - clear - history { padding: 10 px 15 px; background - color: #f8f9fa; border: 1 px solid# ddd; border - radius: 6 px; font - size: 0.9 rem; cursor: pointer; transition: all 0.2 s; width: 100 % ; } #vifed - clear - history: hover { background - color: #e9ecef; } /* Адаптивность */ @media(min - width: 768 px) { h1 { font - size: 2 rem; } .vifed - unit - row label { min - width: 50 px; } } @media(min - width: 768 px) { h1 { font - size: 2 rem; } .vifed - unit - row label { min - width: 50 px; } } /* Мобильные стили (до 767px) */ @media(max - width: 767 px) { .vifed - input - row, .vifed - result - row { flex - direction: column; gap: 10 px; } .vifed - input - row button, .vifed - result - row button { width: 100 % ; padding: 12 px!important; } }
JavaScript:
// Единицы измерения по категориям const units = { length: [{ name: 'Метры', value: 'meters', factor: 1 }, { name: 'Километры', value: 'kilometers', factor: 1000 }, { name: 'Сантиметры', value: 'centimeters', factor: 0.01 }, { name: 'Миллиметры', value: 'millimeters', factor: 0.001 }, { name: 'Мили', value: 'miles', factor: 1609.34 }, { name: 'Ярды', value: 'yards', factor: 0.9144 }, { name: 'Футы', value: 'feet', factor: 0.3048 }, { name: 'Дюймы', value: 'inches', factor: 0.0254 }], weight: [{ name: 'Граммы', value: 'grams', factor: 1 }, { name: 'Килограммы', value: 'kilograms', factor: 1000 }, { name: 'Миллиграммы', value: 'milligrams', factor: 0.001 }, { name: 'Фунты', value: 'pounds', factor: 453.592 }, { name: 'Унции', value: 'ounces', factor: 28.3495 }], volume: [{ name: 'Литр', value: 'liters', factor: 1 }, { name: 'Миллилитр', value: 'milliliters', factor: 0.001 }, { name: 'Галлон (US)', value: 'gallons', factor: 3.78541 }, { name: 'Пинта (US)', value: 'pints', factor: 0.473176 }, { name: 'Куб. метр', value: 'cubic-meters', factor: 1000 }], temperature: [{ name: 'Цельсий', value: 'celsius' }, { name: 'Фаренгейт', value: 'fahrenheit' }, { name: 'Кельвин', value: 'kelvin' }], time: [{ name: 'Секунды', value: 'seconds', factor: 1 }, { name: 'Минуты', value: 'minutes', factor: 60 }, { name: 'Часы', value: 'hours', factor: 3600 }, { name: 'Дни', value: 'days', factor: 86400 }], speed: [{ name: 'м/с', value: 'mps', factor: 1 }, { name: 'км/ч', value: 'kph', factor: 0.277778 }, { name: 'мили/ч', value: 'mph', factor: 0.44704 }, { name: 'узлы', value: 'knots', factor: 0.514444 }] }; // Популярные конвертации const quickConversions = { length: [{ from: 'meters', to: 'feet', label: 'Метры → Футы' }, { from: 'kilometers', to: 'miles', label: 'Километры → Мили' }, { from: 'centimeters', to: 'inches', label: 'Сантиметры → Дюймы' }], weight: [{ from: 'kilograms', to: 'pounds', label: 'Килограммы → Фунты' }, { from: 'grams', to: 'ounces', label: 'Граммы → Унции' }], volume: [{ from: 'liters', to: 'gallons', label: 'Литры → Галлоны' }, { from: 'milliliters', to: 'pints', label: 'Милилитры → Пинты' }], temperature: [{ from: 'celsius', to: 'fahrenheit', label: '°C → °F' }], time: [{ from: 'hours', to: 'minutes', label: 'Часы → Минуты' }], speed: [{ from: 'kph', to: 'mph', label: 'км/ч → мили/ч' }] }; // DOM элементы const categorySelect = document.getElementById('vifed-category'); const fromUnitSelect = document.getElementById('vifed-from-unit'); const toUnitSelect = document.getElementById('vifed-to-unit'); const inputValue = document.getElementById('vifed-input-value'); const outputValue = document.getElementById('vifed-output-value'); const convertBtn = document.getElementById('vifed-convert'); const copyBtn = document.getElementById('vifed-copy'); const quickButtons = document.getElementById('vifed-quick-buttons'); const historyList = document.getElementById('vifed-history-list'); const clearHistoryBtn = document.getElementById('vifed-clear-history'); // История конвертаций let conversionHistory = JSON.parse(localStorage.getItem('conversionHistory')) || []; // Инициализация document.addEventListener('DOMContentLoaded', () => { // Заполняем категории и единицы updateUnits(); // Загружаем историю renderHistory(); // Обработчики событий categorySelect.addEventListener('change', updateUnits); convertBtn.addEventListener('click', convert); copyBtn.addEventListener('click', copyResult); clearHistoryBtn.addEventListener('click', clearHistory); // Устанавливаем фокус на поле ввода inputValue.focus(); }); // Обновление списка единиц function updateUnits() { const category = categorySelect.value; const unitList = units[category]; // Очищаем селекторы fromUnitSelect.innerHTML = ''; toUnitSelect.innerHTML = ''; // Заполняем селекторы unitList.forEach(unit => { const option1 = document.createElement('option'); option1.value = unit.value; option1.textContent = unit.name; const option2 = document.createElement('option'); option2.value = unit.value; option2.textContent = unit.name; fromUnitSelect.appendChild(option1); toUnitSelect.appendChild(option2); }); // Устанавливаем разные единицы по умолчанию if (unitList.length > 1) { toUnitSelect.selectedIndex = 1; } // Обновляем быстрые конвертации updateQuickConversions(category); } // Обновление быстрых конвертаций function updateQuickConversions(category) { quickButtons.innerHTML = ''; if (quickConversions[category]) { quickConversions[category].forEach(conv => { const button = document.createElement('button'); button.textContent = conv.label; button.addEventListener('click', () => { fromUnitSelect.value = conv.from; toUnitSelect.value = conv.to; inputValue.focus(); }); quickButtons.appendChild(button); }); } } // Конвертация function convert() { const category = categorySelect.value; const fromUnit = fromUnitSelect.value; const toUnit = toUnitSelect.value; const value = parseFloat(inputValue.value); if (isNaN(value)) { outputValue.value = ''; return; } let result; // Особый случай для температуры if (category === 'temperature') { result = convertTemperature(value, fromUnit, toUnit); } else { // Для других единиц используем факторы const fromFactor = units[category].find(u => u.value === fromUnit).factor; const toFactor = units[category].find(u => u.value === toUnit).factor; result = (value * fromFactor) / toFactor; } // Округляем до 6 знаков после запятой outputValue.value = parseFloat(result.toFixed(6)); // Добавляем в историю addToHistory(category, fromUnit, toUnit, value, result); } // Конвертация температуры function convertTemperature(value, fromUnit, toUnit) { // Конвертируем в Цельсий как промежуточную let celsius; switch (fromUnit) { case 'celsius': celsius = value; break; case 'fahrenheit': celsius = (value - 32) * 5 / 9; break; case 'kelvin': celsius = value - 273.15; break; } // Конвертируем из Цельсия в нужную единицу switch (toUnit) { case 'celsius': return celsius; case 'fahrenheit': return (celsius * 9 / 5) + 32; case 'kelvin': return celsius + 273.15; } } // Копировать результат function copyResult() { if (!outputValue.value) return; outputValue.select(); document.execCommand('copy'); // Временная подсказка const originalText = copyBtn.textContent; copyBtn.textContent = 'Скопировано!'; setTimeout(() => { copyBtn.textContent = originalText; }, 2000); } // Добавить в историю function addToHistory(category, fromUnit, toUnit, input, output) { const fromName = units[category].find(u => u.value === fromUnit).name; const toName = units[category].find(u => u.value === toUnit).name; const entry = { category, from: fromName, to: toName, input, output, timestamp: new Date().toLocaleString() }; conversionHistory.unshift(entry); if (conversionHistory.length > 10) { conversionHistory.pop(); } localStorage.setItem('conversionHistory', JSON.stringify(conversionHistory)); renderHistory(); } // Отобразить историю function renderHistory() { historyList.innerHTML = ''; conversionHistory.forEach(entry => { const li = document.createElement('li'); li.textContent = `${entry.input} ${entry.from} → ${entry.output} ${entry.to}`; historyList.appendChild(li); }); } // Очистить историю function clearHistory() { conversionHistory = []; localStorage.removeItem('conversionHistory'); renderHistory(); }