1 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
<div>
不是有效的直系<table>
后代使用您的單位到儀表值乘數(shù)創(chuàng)建一個(gè)對(duì)象(考慮可重用性)。
toMeters
在下面的例子中。請(qǐng)記住,輸入值(即使
type="number"
)始終是一個(gè) String - 因此在 JavaScript 中,您必須將該 String 解析為 Float 使用parseFloat(str)
用于
.toFixed()
將精度舍入到定義的小數(shù)點(diǎn)精度
// 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>
添加回答
舉報(bào)