我的問題:
嘿大家。我正在嘗試撰寫一些代碼,根據元素與當前專案的距離來改變元素的亮度。然而,一切都按計劃運行,因為它在當前專案開始回傳“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
}
uj5u.com熱心網友回復:
你需要找到第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,因此代碼不依賴于我所說的隱式全域的恐怖。我強烈建議使用strict mode,所以這就是它應該一直存在的錯誤。
uj5u.com熱心網友回復:
您需要將問題分解為兩個步驟:
- 查找當前專案的索引
- 計算并設定每個專案的亮度
// 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}%)`;
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/459633.html
標籤:javascript html css
下一篇:垂直和水平居中幾個按鈕css
