<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {font-family:Arial;}
form {width:600px;text-align:center;}
input[type=number] {border:2px solid #808080;text-align:right;}
input[type=button] {display:block;margin:auto;}
form span {display:inline-block;width:150px;text-align:right;}
form div {margin:5px;}
</style>
</head>
<body>
<h2>Conversor entre Celsius, Fahrenheit, Kelvin y Rankine</h2>
<form>
<div><span>Celsius/centigrados:</span> <input type="number" name="cel"> ºC</div>
<div><span>Fahrenheit:</span> <input type="number" name="fah"> ºF</div>
<div><span>Kelvin:</span> <input type="number" name="kel"> ºK</div>
<div><span>Rankine:</span> <input type="number" name="ran"> ºR</div>
</form>
</body>
</html>
<script>
const inputs=document.querySelectorAll("form input[type=number]");
inputs.forEach(el=>{
el.addEventListener("keyup", convert);
el.addEventListener("focus", function() {this.select()})
});
/**
* Función que realiza la conversión
*/
function convert(e) {
const cel=document.querySelector("input[name=cel]");
const fah=document.querySelector("input[name=fah]");
const kel=document.querySelector("input[name=kel]");
const ran=document.querySelector("input[name=ran]");
if (this.name=="cel" && this.value) {
fah.value=(parseFloat(cel.value)*1.8+32).toFixed(2);
kel.value=(parseFloat(cel.value)+273.15).toFixed(2);
ran.value=(parseFloat(cel.value)*1.8+491.67).toFixed(2);
} else if (this.name=="fah" && this.value) {
cel.value=((parseFloat(fah.value)-32)/1.8).toFixed(2);
kel.value=(((parseFloat(fah.value)-32)/1.8)+273.15).toFixed(2);
ran.value=(parseFloat(fah.value)-32+491.67).toFixed(2);
} else if (this.name=="kel" && this.value) {
cel.value=(parseFloat(kel.value)-273.15).toFixed(2);
fah.value=(((parseFloat(kel.value)-273.15)*1.8)+32).toFixed(2);
ran.value=(((parseFloat(kel.value)-273.15)*1.8)+491.67).toFixed(2);
} else if (this.name=="ran" && this.value) {
cel.value=((parseFloat(ran.value)-491.67)/1.8).toFixed(2);
fah.value=(parseFloat(ran.value)-491.67+32).toFixed(2);
kel.value=(((parseFloat(ran.value)-491.67)/1.8)+273.15).toFixed(2);
}
}
</script>
Comentarios sobre la versión: Versión 1.0 (0)
No hay comentarios