Hola a todos. Estoy tratando de escribir un código que cambie el brillo de un elemento en función de qué tan lejos esté del elemento actual. Sin embargo, todo funciona de acuerdo con el plan, ya que se mueve hacia abajo en la lista, todos los elementos antes del elemento actual comienzan a devolver "NaN" como su valor. Esto tiene sentido, ya que la variable "currentItemIndex" solo recibe un valor una vez que encuentra la posición del elemento actual, por lo que no hay valor para el "currentItemIndex" hasta que alcanza el elemento actual dentro de la lista.
Intenté declarar la variable "currentItemIndex" antes de que busque el elemento actual, dándole un valor de 0 para comenzar o una cadena vacía. El valor inicial de 0 da como resultado que "currentItemIndex" permanezca en 0 sin importar qué, y la cadena vacía simplemente produce el mismo resultado que cuando no había una variable declarada allí en primer lugar.
No estoy seguro de cómo obtener el "currentItemIndex" antes de buscar el elemento actual y que no afecte la variable cuando busca el elemento actual. ¿Alguien puede ayudarme?
JavaScript:
var items = document.getElementsByClassName('item'); // Gets all of the items for (i = 0; i < items.length; i++) { // For each of the items, this: var itemClass = items[i].classList // Get class of the item if (itemClass.contains('current-item')) { // If it is the current item, this: var currentItemIndex = i; // Set the current item's position to the target's position } var brightness = (100 + (Math.abs(currentItemIndex - i) * 50)); // Calculate how much the brightness should change based on the target's distance from the current item items[i].style.filter = 'brightness(' + brightness + '%)'; // Apply that brightness to the target }Primero deberá encontrar el currentItemIndex , luego hacer el ciclo configurando el brillo:
const items = document.getElementsByClassName("item"); // Gets all of the items let currentItemIndex; for (let i = 0; i < items.length; i++) { // For each of the items, this: const itemClass = items[i].classList // Get class of the item if (itemClass.contains("current-item")) { // If it is the current item, this: currentItemIndex = i; // Set the current item"s position to the target"s position break; } } for (let i = 0; i < items.length; i++) { // For each of the items, this: const brightness = (100 + (Math.abs(currentItemIndex - i) * 50)); // Calculate how much the brightness should change based on the target"s distance from the current item items[i].style.filter = "brightness(" + brightness + "%)"; // Apply that brightness to the target } (Con más contexto, puede ser que haya una forma más concisa de encontrar el índice de ese elemento [el primer ciclo for ], pero lo anterior funciona y es simple).
Nota al margen: agregué una declaración para i , por lo que el código no depende de lo que llamo The Horror of Implicit Globals . Recomiendo encarecidamente usar el modo estricto , por lo que ese es el error que siempre debería haber sido.
Necesita dividir el problema en dos pasos:
// get all of the items as an array let items = Array.from(document.getElementsByClassName('item')); // 1. find the index of the current item let currentItemIndex = items.findIndex(item => items.classList.contains('current-item')); // 2. calculate and set the brightness for every item items.forEach((item, i) => { let brightness = (100 + (Math.abs(currentItemIndex - i) * 50)); item.style.filter = `brightness(${brightness}%)`; });