Продвинутый конвертер единиц

Переводите между единицами длины, веса, объема и других величин.

Исходный код доступен в конце страницы.

Популярные преобразования:

История конвертаций

    Продвинутый конвертер единиц- это мощный инструмент для мгновенного перевода между популярными единицами измерения:

    • Длина: метры ↔ футы, километры ↔ мили.
    • Вес: килограммы ↔ фунты, граммы ↔ унции.
    • Объем: литры ↔ галлоны, миллилитры ↔ пинты.
    • Температура: Цельсий ↔ Фаренгейт ↔ Кельвин.
    • Время: часы ↔ минуты ↔ секунды.
    • Скорость: км/ч ↔ мили/час ↔ м/с.

    Функционал

    • Поддержка 6 категорий единиц в одном инструменте.
    • Популярные конвертации в один клик (например, «Кг → Фунты»).
    • История расчетов — чтобы не потерять результаты.

    Исходный код продвинутого конвертера единиц:

    HTML:

    1. <div class="vifed-container">
    2.  
    3. <!-- Выбор категории -->
    4. <div class="vifed-category-selector">
    5. <select id="vifed-category">
    6. <option value="length">Длина</option>
    7. <option value="weight">Вес</option>
    8. <option value="volume">Объем</option>
    9. <option value="temperature">Температура</option>
    10. <option value="time">Время</option>
    11. <option value="speed">Скорость</option>
    12. </select>
    13. </div>
    14.  
    15. <!-- Блок конвертации -->
    16. <div class="vifed-converter">
    17. <div class="vifed-unit-row">
    18. <label>Из:</label>
    19. <select id="vifed-from-unit"></select>
    20. </div>
    21.  
    22. <div class="vifed-unit-row">
    23. <label>В:</label>
    24. <select id="vifed-to-unit"></select>
    25. </div>
    26.  
    27. <div class="vifed-input-row">
    28. <input type="number" id="vifed-input-value" placeholder="Введите значение">
    29. <button id="vifed-convert">Конвертировать</button>
    30. </div>
    31.  
    32. <div class="vifed-result-row">
    33. <input type="text" id="vifed-output-value" placeholder="Результат" readonly>
    34. <button id="vifed-copy">Копировать</button>
    35. </div>
    36. </div>
    37.  
    38. <!-- Быстрые конвертации -->
    39. <div class="vifed-quick-conversions">
    40. <h3>Популярные преобразования:</h3>
    41. <div class="vifed-quick-buttons" id="vifed-quick-buttons"></div>
    42. </div>
    43.  
    44. <!-- История расчетов -->
    45. <div class="vifed-history">
    46. <h3>История конвертаций</h3>
    47. <ul id="vifed-history-list"></ul>
    48. <button id="vifed-clear-history">Очистить историю</button>
    49. </div>
    50. </div>

    CSS:

    1. /* Основные стили */
    2. : root {
    3. --primary - color: #2c5364;
    4. --secondary-color: # 8 b7355;
    5. --hover - color: #3a7bd5;
    6. --bg-color: # f5f7fa;
    7. --card - bg: #ffffff;
    8. --error - color: #dc3545;
    9. --success - color: #28a745;
    10. }
    11. .vifed - container {
    12. max - width: 800 px;
    13. margin: 0 auto;
    14. background: var (--card - bg);
    15. padding: 25 px;
    16. border - radius: 10 px;
    17. box - shadow: 0 5 px 15 px rgba(0, 0, 0, 0.1);
    18. }
    19. h1 {
    20. color: var (--primary - color);
    21. text - align: center;
    22. margin - bottom: 15 px;
    23. font - size: 1.8 rem;
    24. }
    25. .vifed - description {
    26. text - align: center;
    27. margin - bottom: 25 px;
    28. color: #666;
    29. font-size: 1rem;
    30. }
    31.  
    32. /* Выбор категории */
    33. .vifed-category-selector {
    34. margin-bottom: 20px;
    35. }
    36.  
    37. .vifed-category-selector select {
    38. width: 100%;
    39. padding: 12px 15px;
    40. font-size: 1rem;
    41. border: 1px solid # ddd;
    42. border - radius: 8 px;
    43. background - color: #fff;
    44. appearance: none;
    45. 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");
    46. background - repeat: no - repeat;
    47. background - position: right 10 px center;
    48. background - size: 15 px;
    49. }
    50. /* Блок конвертации */
    51. .vifed - converter {
    52. display: flex;
    53. flex - direction: column;
    54. gap: 15 px;
    55. margin - bottom: 25 px;
    56. }
    57. .vifed - unit - row {
    58. display: flex;
    59. align - items: center;
    60. gap: 10 px;
    61. }
    62. .vifed - unit - row label {
    63. font - size: 1 rem;
    64. color: #555;
    65. min-width: 40px;
    66. }
    67.  
    68. .vifed-unit-row select {
    69. flex: 1;
    70. padding: 12px 15px;
    71. font-size: 1rem;
    72. border: 1px solid # ddd;
    73. border - radius: 8 px;
    74. background - color: #fff;
    75. appearance: none;
    76. 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");
    77. background - repeat: no - repeat;
    78. background - position: right 10 px center;
    79. background - size: 15 px;
    80. }
    81. .vifed - input - row {
    82. display: flex;
    83. gap: 10 px;
    84. margin - top: 10 px;
    85. }
    86. .vifed - input - row input {
    87. flex: 1;
    88. padding: 12 px 15 px;
    89. font - size: 1 rem;
    90. border: 1 px solid# ddd;
    91. border - radius: 8 px;
    92. }
    93. .vifed - input - row button {
    94. padding: 0 20 px;
    95. border: none;
    96. border - radius: 8 px;
    97. font - size: 1 rem;
    98. cursor: pointer;
    99. transition: all 0.2 s;
    100. }
    101. #vifed - convert {
    102. background - color: var (--primary - color);
    103. color: white;
    104. }
    105. #vifed - convert: hover {
    106. background - color: var (--hover - color);
    107. }
    108. .vifed - result - row {
    109. display: flex;
    110. gap: 10 px;
    111. margin - top: 5 px;
    112. }
    113. .vifed - result - row input {
    114. flex: 1;
    115. padding: 12 px 15 px;
    116. font - size: 1 rem;
    117. border: 1 px solid# ddd;
    118. border - radius: 8 px;
    119. background - color: #f9f9f9;
    120. }
    121. #vifed - copy {
    122. background - color: var (--secondary - color);
    123. color: white;
    124. padding: 0 15 px;
    125. border: none;
    126. border - radius: 8 px;
    127. font - size: 1 rem;
    128. cursor: pointer;
    129. transition: all 0.2 s;
    130. }
    131. #vifed - copy: hover {
    132. background - color: #9d8260;
    133. }
    134.  
    135. /* Быстрые конвертации */
    136. .vifed-quick-conversions {
    137. margin-bottom: 25px;
    138. }
    139.  
    140. .vifed-quick-conversions h3 {
    141. margin-bottom: 12px;
    142. font-size: 1.1rem;
    143. color: var(--primary-color);
    144. }
    145.  
    146. .vifed-quick-buttons {
    147. display: flex;
    148. flex-wrap: wrap;
    149. gap: 8px;
    150. }
    151.  
    152. .vifed-quick-buttons button {
    153. padding: 8px 12px;
    154. background-color: # e9ecef;
    155. border: none;
    156. border - radius: 6 px;
    157. font - size: 0.85 rem;
    158. cursor: pointer;
    159. transition: background - color 0.2 s;
    160. }
    161. .vifed - quick - buttons button: hover {
    162. background - color: #d1d7dc;
    163. }
    164. /* История расчетов */
    165. .vifed - history {
    166. border - top: 1 px solid# eee;
    167. padding - top: 20 px;
    168. }
    169. .vifed - history h3 {
    170. margin - bottom: 12 px;
    171. font - size: 1.1 rem;
    172. color: var (--primary - color);
    173. }
    174. #vifed - history - list {
    175. list - style: none;
    176. margin - bottom: 15 px;
    177. }
    178. #vifed - history - list li {
    179. padding: 10 px 0;
    180. border - bottom: 1 px solid# f0f0f0;
    181. font - size: 0.9 rem;
    182. }
    183. #vifed - clear - history {
    184. padding: 10 px 15 px;
    185. background - color: #f8f9fa;
    186. border: 1 px solid# ddd;
    187. border - radius: 6 px;
    188. font - size: 0.9 rem;
    189. cursor: pointer;
    190. transition: all 0.2 s;
    191. width: 100 % ;
    192. }
    193. #vifed - clear - history: hover {
    194. background - color: #e9ecef;
    195. }
    196. /* Адаптивность */
    197. @media(min - width: 768 px) {
    198. h1 {
    199. font - size: 2 rem;
    200. }
    201. .vifed - unit - row label {
    202. min - width: 50 px;
    203. }
    204. }
    205. @media(min - width: 768 px) {
    206. h1 {
    207. font - size: 2 rem;
    208. }
    209. .vifed - unit - row label {
    210. min - width: 50 px;
    211. }
    212. }
    213. /* Мобильные стили (до 767px) */
    214. @media(max - width: 767 px) {
    215. .vifed - input - row,
    216. .vifed - result - row {
    217. flex - direction: column;
    218. gap: 10 px;
    219. }
    220. .vifed - input - row button,
    221. .vifed - result - row button {
    222. width: 100 % ;
    223. padding: 12 px!important;
    224. }
    225. }

    JavaScript:

    1. // Единицы измерения по категориям
    2. const units = {
    3. length: [{
    4. name: 'Метры',
    5. value: 'meters',
    6. factor: 1
    7. }, {
    8. name: 'Километры',
    9. value: 'kilometers',
    10. factor: 1000
    11. }, {
    12. name: 'Сантиметры',
    13. value: 'centimeters',
    14. factor: 0.01
    15. }, {
    16. name: 'Миллиметры',
    17. value: 'millimeters',
    18. factor: 0.001
    19. }, {
    20. name: 'Мили',
    21. value: 'miles',
    22. factor: 1609.34
    23. }, {
    24. name: 'Ярды',
    25. value: 'yards',
    26. factor: 0.9144
    27. }, {
    28. name: 'Футы',
    29. value: 'feet',
    30. factor: 0.3048
    31. }, {
    32. name: 'Дюймы',
    33. value: 'inches',
    34. factor: 0.0254
    35. }],
    36. weight: [{
    37. name: 'Граммы',
    38. value: 'grams',
    39. factor: 1
    40. }, {
    41. name: 'Килограммы',
    42. value: 'kilograms',
    43. factor: 1000
    44. }, {
    45. name: 'Миллиграммы',
    46. value: 'milligrams',
    47. factor: 0.001
    48. }, {
    49. name: 'Фунты',
    50. value: 'pounds',
    51. factor: 453.592
    52. }, {
    53. name: 'Унции',
    54. value: 'ounces',
    55. factor: 28.3495
    56. }],
    57. volume: [{
    58. name: 'Литр',
    59. value: 'liters',
    60. factor: 1
    61. }, {
    62. name: 'Миллилитр',
    63. value: 'milliliters',
    64. factor: 0.001
    65. }, {
    66. name: 'Галлон (US)',
    67. value: 'gallons',
    68. factor: 3.78541
    69. }, {
    70. name: 'Пинта (US)',
    71. value: 'pints',
    72. factor: 0.473176
    73. }, {
    74. name: 'Куб. метр',
    75. value: 'cubic-meters',
    76. factor: 1000
    77. }],
    78. temperature: [{
    79. name: 'Цельсий',
    80. value: 'celsius'
    81. }, {
    82. name: 'Фаренгейт',
    83. value: 'fahrenheit'
    84. }, {
    85. name: 'Кельвин',
    86. value: 'kelvin'
    87. }],
    88. time: [{
    89. name: 'Секунды',
    90. value: 'seconds',
    91. factor: 1
    92. }, {
    93. name: 'Минуты',
    94. value: 'minutes',
    95. factor: 60
    96. }, {
    97. name: 'Часы',
    98. value: 'hours',
    99. factor: 3600
    100. }, {
    101. name: 'Дни',
    102. value: 'days',
    103. factor: 86400
    104. }],
    105. speed: [{
    106. name: 'м/с',
    107. value: 'mps',
    108. factor: 1
    109. }, {
    110. name: 'км/ч',
    111. value: 'kph',
    112. factor: 0.277778
    113. }, {
    114. name: 'мили/ч',
    115. value: 'mph',
    116. factor: 0.44704
    117. }, {
    118. name: 'узлы',
    119. value: 'knots',
    120. factor: 0.514444
    121. }]
    122. };
    123. // Популярные конвертации
    124. const quickConversions = {
    125. length: [{
    126. from: 'meters',
    127. to: 'feet',
    128. label: 'Метры &rarr; Футы'
    129. }, {
    130. from: 'kilometers',
    131. to: 'miles',
    132. label: 'Километры &rarr; Мили'
    133. }, {
    134. from: 'centimeters',
    135. to: 'inches',
    136. label: 'Сантиметры &rarr; Дюймы'
    137. }],
    138. weight: [{
    139. from: 'kilograms',
    140. to: 'pounds',
    141. label: 'Килограммы &rarr; Фунты'
    142. }, {
    143. from: 'grams',
    144. to: 'ounces',
    145. label: 'Граммы &rarr; Унции'
    146. }],
    147. volume: [{
    148. from: 'liters',
    149. to: 'gallons',
    150. label: 'Литры &rarr; Галлоны'
    151. }, {
    152. from: 'milliliters',
    153. to: 'pints',
    154. label: 'Милилитры &rarr; Пинты'
    155. }],
    156. temperature: [{
    157. from: 'celsius',
    158. to: 'fahrenheit',
    159. label: '&deg;C &rarr; &deg;F'
    160. }],
    161. time: [{
    162. from: 'hours',
    163. to: 'minutes',
    164. label: 'Часы &rarr; Минуты'
    165. }],
    166. speed: [{
    167. from: 'kph',
    168. to: 'mph',
    169. label: 'км/ч &rarr; мили/ч'
    170. }]
    171. };
    172. // DOM элементы
    173. const categorySelect = document.getElementById('vifed-category');
    174. const fromUnitSelect = document.getElementById('vifed-from-unit');
    175. const toUnitSelect = document.getElementById('vifed-to-unit');
    176. const inputValue = document.getElementById('vifed-input-value');
    177. const outputValue = document.getElementById('vifed-output-value');
    178. const convertBtn = document.getElementById('vifed-convert');
    179. const copyBtn = document.getElementById('vifed-copy');
    180. const quickButtons = document.getElementById('vifed-quick-buttons');
    181. const historyList = document.getElementById('vifed-history-list');
    182. const clearHistoryBtn = document.getElementById('vifed-clear-history');
    183. // История конвертаций
    184. let conversionHistory = JSON.parse(localStorage.getItem('conversionHistory')) || [];
    185. // Инициализация
    186. document.addEventListener('DOMContentLoaded', () => {
    187. // Заполняем категории и единицы
    188. updateUnits();
    189. // Загружаем историю
    190. renderHistory();
    191. // Обработчики событий
    192. categorySelect.addEventListener('change', updateUnits);
    193. convertBtn.addEventListener('click', convert);
    194. copyBtn.addEventListener('click', copyResult);
    195. clearHistoryBtn.addEventListener('click', clearHistory);
    196. // Устанавливаем фокус на поле ввода
    197. inputValue.focus();
    198. });
    199. // Обновление списка единиц
    200. function updateUnits() {
    201. const category = categorySelect.value;
    202. const unitList = units[category];
    203. // Очищаем селекторы
    204. fromUnitSelect.innerHTML = '';
    205. toUnitSelect.innerHTML = '';
    206. // Заполняем селекторы
    207. unitList.forEach(unit => {
    208. const option1 = document.createElement('option');
    209. option1.value = unit.value;
    210. option1.textContent = unit.name;
    211. const option2 = document.createElement('option');
    212. option2.value = unit.value;
    213. option2.textContent = unit.name;
    214. fromUnitSelect.appendChild(option1);
    215. toUnitSelect.appendChild(option2);
    216. });
    217. // Устанавливаем разные единицы по умолчанию
    218. if (unitList.length > 1) {
    219. toUnitSelect.selectedIndex = 1;
    220. }
    221. // Обновляем быстрые конвертации
    222. updateQuickConversions(category);
    223. }
    224. // Обновление быстрых конвертаций
    225. function updateQuickConversions(category) {
    226. quickButtons.innerHTML = '';
    227. if (quickConversions[category]) {
    228. quickConversions[category].forEach(conv => {
    229. const button = document.createElement('button');
    230. button.textContent = conv.label;
    231. button.addEventListener('click', () => {
    232. fromUnitSelect.value = conv.from;
    233. toUnitSelect.value = conv.to;
    234. inputValue.focus();
    235. });
    236. quickButtons.appendChild(button);
    237. });
    238. }
    239. }
    240. // Конвертация
    241. function convert() {
    242. const category = categorySelect.value;
    243. const fromUnit = fromUnitSelect.value;
    244. const toUnit = toUnitSelect.value;
    245. const value = parseFloat(inputValue.value);
    246. if (isNaN(value)) {
    247. outputValue.value = '';
    248. return;
    249. }
    250. let result;
    251. // Особый случай для температуры
    252. if (category === 'temperature') {
    253. result = convertTemperature(value, fromUnit, toUnit);
    254. } else {
    255. // Для других единиц используем факторы
    256. const fromFactor = units[category].find(u => u.value === fromUnit).factor;
    257. const toFactor = units[category].find(u => u.value === toUnit).factor;
    258. result = (value * fromFactor) / toFactor;
    259. }
    260. // Округляем до 6 знаков после запятой
    261. outputValue.value = parseFloat(result.toFixed(6));
    262. // Добавляем в историю
    263. addToHistory(category, fromUnit, toUnit, value, result);
    264. }
    265. // Конвертация температуры
    266. function convertTemperature(value, fromUnit, toUnit) {
    267. // Конвертируем в Цельсий как промежуточную
    268. let celsius;
    269. switch (fromUnit) {
    270. case 'celsius':
    271. celsius = value;
    272. break;
    273. case 'fahrenheit':
    274. celsius = (value - 32) * 5 / 9;
    275. break;
    276. case 'kelvin':
    277. celsius = value - 273.15;
    278. break;
    279. }
    280. // Конвертируем из Цельсия в нужную единицу
    281. switch (toUnit) {
    282. case 'celsius':
    283. return celsius;
    284. case 'fahrenheit':
    285. return (celsius * 9 / 5) + 32;
    286. case 'kelvin':
    287. return celsius + 273.15;
    288. }
    289. }
    290. // Копировать результат
    291. function copyResult() {
    292. if (!outputValue.value) return;
    293. outputValue.select();
    294. document.execCommand('copy');
    295. // Временная подсказка
    296. const originalText = copyBtn.textContent;
    297. copyBtn.textContent = 'Скопировано!';
    298. setTimeout(() => {
    299. copyBtn.textContent = originalText;
    300. }, 2000);
    301. }
    302. // Добавить в историю
    303. function addToHistory(category, fromUnit, toUnit, input, output) {
    304. const fromName = units[category].find(u => u.value === fromUnit).name;
    305. const toName = units[category].find(u => u.value === toUnit).name;
    306. const entry = {
    307. category,
    308. from: fromName,
    309. to: toName,
    310. input,
    311. output,
    312. timestamp: new Date().toLocaleString()
    313. };
    314. conversionHistory.unshift(entry);
    315. if (conversionHistory.length > 10) {
    316. conversionHistory.pop();
    317. }
    318. localStorage.setItem('conversionHistory', JSON.stringify(conversionHistory));
    319. renderHistory();
    320. }
    321. // Отобразить историю
    322. function renderHistory() {
    323. historyList.innerHTML = '';
    324. conversionHistory.forEach(entry => {
    325. const li = document.createElement('li');
    326. li.textContent = `${entry.input} ${entry.from} &rarr; ${entry.output} ${entry.to}`;
    327. historyList.appendChild(li);
    328. });
    329. }
    330. // Очистить историю
    331. function clearHistory() {
    332. conversionHistory = [];
    333. localStorage.removeItem('conversionHistory');
    334. renderHistory();
    335. }
    Нет комментариев. Ваш будет первым!
    Посещая этот сайт, вы соглашаетесь с тем, что мы используем файлы cookie.