console
const standard = '米'
const units = [
['千米', 1000],
['米', 1],
['分米', 1/10],
['厘米', 1/100],
['毫米', 1/1000]
];
function initUnits() {
const options = [];
for(const unit of units) {
options.push('<option value=' + unit[1] + '>' + unit[0] + '</option>');
}
document.getElementById('units_in').innerHTML = options.join('');
document.getElementById('units_out').innerHTML = options.join('');
}
function getInput() {
return document.getElementById('input').value * 1;
}
function setOutput(val) {
document.getElementById('output').innerText = val;
}
function getInputUnitFactor() {
return document.getElementById('units_in').value * 1;
}
function getOutputUnitFactor() {
return document.getElementById('units_out').value * 1;
}
function convert() {
const input = getInput();
const factorIn = getInputUnitFactor();
const factorOut = getOutputUnitFactor();
const standard = input * factorIn;
const output = standard / factorOut;
setOutput(output)
}
initUnits();
convert();
<html>
<head>
<title>单位换算</title>
</head>
<body>
<div class='container flex flex-c fvc'>
<div class='title flex fvc'>单位转换神器</div>
<div class='subtitle'>EASY UNIT CONVERTER</div>
<div class="intro flex fhc fvc">
<i>请你来实现一个单位自动转换神器,通过这个神器,可以将一个数据单位自动转换位另外一个单位!</i>
</div>
<div class='main flex'>
<input id='input' placeholder='输入数字' value='100' onChange='convert()'/>
<select id='units_in' onChange='convert()'></select>
<span style='margin: 0 10'> = </span>
<span id='output' onChange='convert()'></span>
<select id='units_out' onChange='convert()'></select>
</div>
<div class="intro flex flex-c fhc">
<b>1. 请你再来开发一个时间单位转换器,或者你还能开发什么单位转换器?</b>
<b>2. 如果让你来设计个衡量长度的单位,你觉得可以吗?</b>
</div>
</div>
</body>
</html>
html, body {
background: #fff;
font-family: PingFangSC
}
.flex {
display: flex;
}
.flex-c {
flex-direction: column;
}
.fhc {
justify-content: center;
}
.fvc {
align-items: center;
}
.container {
width: 100%;
height: 200px;
margin: auto;
}
.main {
margin: 60px 0px;
}
.title {
font-size: 24px;
height: 80px;
}
.subtitle {
height: 40px;
font-size: 14px;
color: #999;
}
.intro {
height: 100px;
color: #999;
font-size: 12px;
}
#input, #output {
width: 80px;
border: none;
border-bottom: 1px solid #666;
}
#output {
min-width: 40px;
padding: 0px 10px;
}
select {
width: 80px;
border: none;
border-bottom: 1px solid #666;
}
#units_in {
color: red;
font-weight: bold;
}
#units_out {
color: green;
font-weight: bold;
}