1 回答
TA贡献1804条经验 获得超2个赞
<div>
不是有效的直系<table>
后代使用您的单位到仪表值乘数创建一个对象(考虑可重用性)。
toMeters
在下面的例子中。请记住,输入值(即使
type="number"
)始终是一个 String - 因此在 JavaScript 中,您必须将该 String 解析为 Float 使用parseFloat(str)
用于
.toFixed()
将精度舍入到定义的小数点精度
// Just some nifty helpers to get DOM element/s
const ELS = (sel, EL) => (EL || document).querySelectorAll(sel);
const EL = (sel, EL) => (EL || document).querySelector(sel);
// Cache your elements
const EL_result = EL("#result");
const EL_w = EL("#width");
const EL_l = EL("#length");
const EL_d = EL("#depth");
const EL_uw = EL("#unit-width");
const EL_ul = EL("#unit-length");
const EL_ud = EL("#unit-depth");
const toMeters = (str = "1", unit = "m") => str.trim() * {
m : 1,
cm: 100,
in: 39.37,
ft: 3.28084,
yd: 1.09361
}[unit];
function calcVol() {
const w = toMeters(EL_w.value, EL_uw.value);
const l = toMeters(EL_l.value, EL_ul.value);
const d = toMeters(EL_d.value, EL_ud.value);
const tot = w * l * d;
EL_result.textContent = Number(tot.toFixed(5));
}
ELS(".calc").forEach(el => el.addEventListener("input", calcVol));
// init!
calcVol();
span.label {display: inline-block; min-width: 80px; font:14px sans-serif;}
<span class="label">Width</span>
<input id="width" class="calc" type="number" value="1" min="0" step="0.1">
<select id="unit-width" class="calc">
<option value="m">Metres</option>
<option value="cm">Centimeter</option>
<option value="in">Inches</option>
<option value="ft">Feet</option>
<option value="yd">Yards</option>
</select>
<br>
<span class="label">Length</span>
<input id="length" class="calc" type="number" value="1" min="0" step="0.1">
<select id="unit-length" class="calc">
<option value="m">Metres</option>
<option value="cm">Centimeter</option>
<option value="in">Inches</option>
<option value="ft">Feet</option>
<option value="yd">Yards</option>
</select>
<br>
<span class="label">Depth</span>
<input id="depth" class="calc" type="number" value="1" min="0" step="0.1">
<select id="unit-depth" class="calc">
<option value="m">Metres</option>
<option value="cm">Centimeter</option>
<option value="in">Inches</option>
<option value="ft">Feet</option>
<option value="yd">Yards</option>
</select>
<br>
<span class="label">VOLUME:</span>
<span id="result">0</span> m<sup>3</sup>
添加回答
举报