線上運(yùn)行,可以直接打開:溫度單位換算計(jì)算器(在線計(jì)算器)
? ? ? ?作為程序員,沒有合適的工具,就得手搓一個终议,PC端,移動端均可適用。廢話不多說穴张,直接上代碼细燎。
HTML:
<div class="calculator"><label for="inputValue">輸入溫度值:</label> <input id="inputValue" type="number" placeholder="請輸入數(shù)值"> <label for="inputUnit">選擇輸入單位:</label><select id="inputUnit"><option value="celsius">攝氏度 (°C)</option><option value="fahrenheit">華氏度 (°F)</option><option value="kelvin">開爾文 (K)</option></select><label for="outputUnit">選擇輸出單位:</label><select id="outputUnit"><option value="celsius">攝氏度 (°C)</option><option value="fahrenheit">華氏度 (°F)</option><option value="kelvin">開爾文 (K)</option></select><button onclick="convertTemperature()">計(jì)算</button><div class="result"><p>轉(zhuǎn)換結(jié)果:</p><p id="outputValue">0</p></div></div>
JS:
function convertTemperature() { const inputValue = parseFloat(document.getElementById('inputValue').value); const inputUnit = document.getElementById('inputUnit').value; const outputUnit = document.getElementById('outputUnit').value; if (isNaN(inputValue)) { alert('請輸入有效的溫度值'); return; } let valueInCelsius; // Convert input value to Celsius switch (inputUnit) { case 'celsius': valueInCelsius = inputValue; break; case 'fahrenheit': valueInCelsius = (inputValue - 32) * 5/9; break; case 'kelvin': valueInCelsius = inputValue - 273.15; break; } // Convert Celsius to output unit let convertedValue; switch (outputUnit) { case 'celsius': convertedValue = valueInCelsius; break; case 'fahrenheit': convertedValue = valueInCelsius * 9/5 + 32; break; case 'kelvin': convertedValue = valueInCelsius + 273.15; break; } document.getElementById('outputValue').textContent = convertedValue.toFixed(2); }
CSS:
.calculator { width: 300px; background-color: #333; color: white; padding: 20px; border-radius: 10px; box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3); } label { display: block; margin-bottom: 10px; font-size: 16px; } input, select { width: 100%!important; padding: 10px!important; margin-bottom: 20px; color: #000000; border-radius: 5px; border: 1px solid #555; font-size: 16px!important; background-color: #ffffff!important; } button { width: 100%; padding: 10px; background-color: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; } button:hover { background-color: orange; } .result { margin-top: 20px; text-align: center; } option { background-color: #ffffff; } p { font-size: 18px; margin-top: 5px!important; }