我正在创建一个带有导航栏和一些JavaScript的网站,这些JavaScript设置了div的位置和背景渐变(类:bubble
),该div根据用户滚动到的位置来突出显示导航栏项目。这是我的代码的每一小部分:
const sections = document.querySelectorAll('selection');
const bubble = document.querySelector('.bubble');
const gradient = 'linear-gradient(to right top, #000428, #004e92)';
const options = {
threshold: 0.7
}
let observer = new IntersectionObserver(navCheck, options);
function navCheck(entries) {
entries.forEach(entry => {
const className = entry.target.className;
const activeAnchor = document.querySelector(`[data-page=${className}]`);
const gradientIndex = entry.target.getAttribute(`data-index`)
const coords = activeAnchor.getBoundingClientRect();
const directions = {
height: coords.height,
width: coords.width,
top: coords.top,
left: coords.left
};
if (entry.isIntersecting) {
bubble.style.setProperty('left', `${directions.left}px`)
bubble.style.setProperty('top', `${directions.top}px`)
bubble.style.setProperty('width', `${directions.width}px`)
bubble.style.setProperty('height', `${directions.height}px`)
}
});
}
sections.forEach(section => {
observer.observe(section);
});
现在,我是JavaScript的超级新手,无法找出为什么它什么也没做。有人可以帮我吗?
似乎是相同的代码。
我更改了:
const activeAnchor = document.querySelector("[data-page="+ CSS.escape(className) + "]");
并且有效,但不要问我为什么。
这里是我的完整JavaScript文件:
const section = document.querySelectorAll('section');
const bubble = document.querySelector('.bubble');
const gradients = [
"linear-gradient(to right top, #56ab2f, #a8e063)",
"linear-gradient(to right top, #cb2d3e, #ef473a)",
"linear-gradient(to right top, #5A3F37, #2c7744)",
];
const options = {
threshold: 0.7
}
let observer = new IntersectionObserver(navCheck, options);
function navCheck(entries) {
entries.forEach(entry => {
const className = entry.target.className;
const activeAnchor = document.querySelector("[data-page="+ CSS.escape(className) + "]");
const gradientIndex = entry.target.getAttribute("data-index");
const coords = activeAnchor.getBoundingClientRect();
const directions = {
height: coords.height,
width: coords.width,
top: coords.top,
left: coords.left
};
if (entry.isIntersecting){
bubble.style.setProperty('left', directions.left.toString() + 'px');
bubble.style.setProperty('top', directions.top.toString() + 'px');
bubble.style.setProperty('width', directions.width.toString() + 'px');
bubble.style.setProperty('height', directions.height.toString() + 'px');
console.log(bubble.style);
}
});
}
section.forEach(section => {
observer.observe(section);
});