返回模板
Instant unit converter
A two-way length and temperature converter running in vanilla JavaScript.
完整源码
1 行 · 1.3 KB<style>*{box-sizing:border-box}body{margin:0;font-family:Inter,system-ui,sans-serif;background:#f6f7fb;color:#172033}button,a{font:inherit}.wrap{width:min(960px,calc(100% - 32px));margin:auto}</style><style>main{min-height:100vh;display:grid;place-items:center;padding:24px}.box{width:min(440px,100%);background:#fff;border:1px solid #e2e8f0;border-radius:18px;padding:28px}.row{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:16px}label{display:block;font-size:13px;font-weight:700;margin-bottom:6px}input{width:100%;padding:11px;border:1px solid #cbd5e1;border-radius:9px;font:inherit}</style><main><div class="box"><h1 style="margin:0 0 6px">Unit Converter</h1><p style="margin:0;color:#64748b">Live Celsius ↔ Fahrenheit</p><div class="row"><div><label for="c">Celsius (°C)</label><input id="c" type="number" value="25" oninput="fromC()"></div><div><label for="f">Fahrenheit (°F)</label><input id="f" type="number" value="77" oninput="fromF()"></div></div></div></main><script>function fromC(){const v=parseFloat(document.getElementById("c").value);if(!isNaN(v))document.getElementById("f").value=(v*9/5+32).toFixed(1)}function fromF(){const v=parseFloat(document.getElementById("f").value);if(!isNaN(v))document.getElementById("c").value=((v-32)*5/9).toFixed(1)}</script>适用场景
不到 40 行代码即可实现的双向实时单位换算工具模板。
布局原理
两个并排输入框各自监听输入事件并同步更新对方数值,逻辑简洁清晰。
如何定制
可轻松改成长度、px/rem 换算或汇率工具,并在下方附带换算公式说明。
发布前检查
测试清空输入框、负数(如 -40 °C)与小数精度表现。