Tengo una variable (X) que puede ir de 0 a 100. También tengo otra variable (Y) que va de -90 a 90. Quiero hacer que si la variable X es 0 entonces Y es igual a -90 , la variable X es 1, luego la variable Y es -88.2 (ha bajado 1.8) hasta que X sea 100 e Y sea 90. ¿Cómo haría esto?
son solo matematicas simples
y = -90 + 1.8 * x; function getY(event){ document.getElementById('y').value = (-90 + 1.8 * event.target.value).toFixed(2); } X : <input type="number" min="0" max="100" id="x" onchange="getY(event)" value='0'/> Y: <input disabled id="y" value='-90'/>Puede cambiar el valor de cualquiera de los controles deslizantes de rango. El valor del otro control deslizante se calculará y establecerá en consecuencia:
const [one,two]=["one","two"].map(e=>document.getElementById(e)), cnvrt=(two.max-two.min)/(one.max-one.min); document.body.addEventListener("input",ev=>{ if (ev.target===one) two.value=+two.min+cnvrt*one.value; else one.value=(two.value-two.min)/cnvrt; [one,two].forEach(el=>el.nextElementSibling.textContent=el.value) }) <input type="range" min="0" max="100" id="one" value="0"><span></span><br> <input type="range" min="-90" max="90" id="two" value=-90><span></span>La función de conversión aislada sería:
function convert(x){ const targetMin=-90, cnvrt=(90 -targetMin) /(100 - 0); return targetMin+cnvrt*x; }Use Object.defineProperties para declarar sus variables asignando propiedades X, Y al objeto de la window , si desea que sus variables sean variables globales , y cree Y como una propiedad de acceso (también conocido como captador , básicamente una propiedad calculada):
Object.defineProperties(window, { _X: { value: undefined, writable: true, enumerable: true, configurable: true, }, X: { set: function(val) { const currentVal = Number(val); if (isNaN(currentVal) || currentVal < 0 || currentVal > 100) { throw(`Failed to assign ${val} to X. It can only be assigned numeric values from 0 to 100`); } else { this._X = val; } }, get: function() { return this._X }, enumerable: true, configurable: true, }, Y: { get: function() { return - 90 + this.X * 1.8 }, enumerable: true, configurable: true, } }); X = 100; console.log(Y); // 90 X = 0; console.log(Y); // -90 X = 50; console.log(Y); // 0 try { X = 101; // Failed to assign 101 to X. It can only be assigned numeric values from 0 to 100 } catch (e) { console.error(e); } Nota: también agregué una protección que no permitirá asignar valores no válidos a X .