【发布时间】:2020-08-13 02:39:33
【问题描述】:
我正在处理 javascript IntersectionObserver 属性。
我想从colors 数组中获取颜色以将entry.target.style.backgroundColor= col; //changing to background color to the color from colors array 放在action 函数中。
但我得到的只有blue,这是colors数组的最后一个。
如何从数组中获取每种颜色并使其发挥作用? 另外,向上滚动时是否可以将颜色恢复为原始背景颜色?
const sections = document.querySelectorAll('section');
const colors = ['green','brown', 'blue'];
for(let i=0; i < colors.length; i ++) {
col = colors[i];
}
const action = function (entries) {
entries.forEach(entry => {
if(entry.isIntersecting) {
entry.target.style.backgroundColor= col; //changing to background color to the color from colors array
} else {
return false; // going back to original background color???
}
});
}
const options = {
root: null,
rootMargin: "30% 0px",
threshold: 1
};
const observer = new IntersectionObserver(action, options);
sections.forEach(section => {
observer.observe(section);
});
header { height: 100vh; background: #ccc;}
.block {
position: relative;
width: 100%;
height: 100vh;
transition: .5s;
}
.block1 {background: #666;}
.block2 { background: #aaa;}
.block3 { background: #333;}
<header>header</header>
<section class="block block1">green</section>
<section class="block block2">brown</section>
<section class="block block3">blue</section>
【问题讨论】:
-
您想使用数组中的哪种颜色?现在,您的 for 循环将
colors数组中的最后一项分配给col -
@Maaz Syed Adeeb 感谢您的评论。我想要每一种颜色。块 1 为绿色,块 2 为棕色,块 3 为蓝色。我不知道如何让每种颜色在函数中使用...
标签: javascript arrays function for-loop intersection-observer