gpt4 book ai didi

javascript - 如何更新依赖代码的变量? (JavaScript)

转载 作者:行者123 更新时间:2023-12-05 09:02:06 25 4
gpt4 key购买 nike

我的问题:

大家好。我正在尝试编写一些代码,根据它与当前元素的距离来改变元素的亮度。然而,一切都按计划运行,因为它在列表中向下移动,当前元素开始返回“NaN”作为它们的值之前的所有元素。这是有道理的,因为“currentItemIndex”变量只有在找到当前项的位置后才会被赋予一个值,因此“currentItemIndex”在到达列表中的当前项之前没有值。

我尝试过的:

我试过在搜索当前元素之前声明“currentItemIndex”变量,给它一个值 0 开始或一个空字符串。 0 的起始值导致“currentItemIndex”无论如何都保持为 0,而空字符串只会产生与最初没有在那里声明变量时相同的结果。

我不确定如何在搜索当前项之前获取“currentItemIndex”,并且在检查当前项时不影响变量。有人能帮帮我吗?

我的代码:

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

}

最佳答案

您需要先找到currentItemIndex然后循环设置亮度:

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
}

(有了更多上下文,可能有更简洁的方法来查找该元素的索引 [第一个 for 循环],但上面的方法很简单。)


旁注:我为 i 添加了声明,因此代码不依赖于我所说的 The Horror of Implicit Globals。 .我强烈建议使用 strict mode ,所以这应该是错误。

关于javascript - 如何更新依赖代码的变量? (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71942902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com