线上运行,可以直接打开:温度单位换算计算器(在线计算器)

作为程序员,没有合适的工具,就得手搓一个,PC端,移动端均可适用。废话不多说,直接上代码。
HTML:
<div class=”calculator”><label for=”inputValue”>输入温度值:</label> <input id=”inputValue” type=”number” placeholder=”请输入数值”> <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()”>计算</button><div class=”result”><p>转换结果:</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;
}


















暂无评论内容