如何使此转换功能在两个方向上都有效?

How do I make this conversion function work in both directions?

我是 JS 新手,我无法仅通过输入完成转换器,我解释一下问题! 我们有两个输入,米和英尺。当我将一个数字传输到英尺时,我得到以米为单位的结果。我想对 Meters 做同样的思考。反之亦然

let metresEl = document.getElementById('inputMetres');


function LengthConverter(valNum) {
    metresEl.value = valNum/3.2808;
}
  <div class="container">
    <div class="form-group">
      <label>Feet</label>
      <input type="number" id="inputFeet" placeholder="Feet" oninput="LengthConverter(this.value)" onchange="LengthConverter(this.value)" >
    </div>
    <div class="form-group">
      <label>Metres</label>
      <input type="number" id="inputMetres" placeholder="Metres">
    </div>
  </div>

您可以在 LengthConvertor 函数中添加另一个参数,该参数表示输入单位(米或英尺)并在函数内使用 if 进行相应的转换。

function LengthConverter(valNum, inputUnit) {
   if(inputUnit === 'feet')
    metresEl.value = valNum/3.2808;
   if(inputUnit === 'meter')
    feetsEL.value = valNum * 3.2808;
}


<div class="container">
    <div class="form-group">
      <label>Feet</label>
      <input type="number" id="inputFeet" placeholder="Feet" oninput="LengthConverter(this.value,"feet")" onchange="LengthConverter(this.value,"feet")" >
    </div>
    <div class="form-group">
      <label>Metres</label>
      <input type="number" id="inputMetres" placeholder="Metres" oninput="LengthConverter(this.value,"meter")" onchange="LengthConverter(this.value,"meter")" >
    </div>
  </div>

添加了反向转换:

let metresEl = document.getElementById('inputMetres');
let feetEl = document.getElementById('inputFeet');


function FeetToMetres(valNum) {
    metresEl.value = valNum/3.2808;
}

function MetresToFeet(valNum) {
    feetEl.value = 3.2808*valNum;
}
  <div class="container">
    <div class="form-group">
      <label>Feet</label>
      <input type="number" id="inputFeet" placeholder="Feet" oninput="FeetToMetres(this.value)" onchange="FeetToMetres(this.value)" >
    </div>
    <div class="form-group">
      <label>Metres</label>
      <input type="number" id="inputMetres" placeholder="Metres" oninput="MetresToFeet(this.value)" onchange="MetresToFeet(this.value)">
    </div>
  </div>

您可以为每个输入添加一个 element.addEvenetListener,当您有机会获得它的值时,转换并输入正确的输入。

let metresEl = document.getElementById('inputMetres');
let feetsEl = document.getElementById('inputFeets');

metresEl.addEventListener('change', yourCode);
feetsEl.addEventListener('change', yourCode);

例如,如果米输入发生变化,您将转换为英尺并添加到英尺输入。