JavaScript element.style.setProperty() 不起作用



我正在创建一个带有导航栏和一些JavaScript的网站,用于设置div(类:bubble(的位置和背景渐变,该梯度根据用户滚动到的位置突出显示导航栏项。这是我代码的每一点:

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 非常陌生,无法找出为什么它没有做任何事情。谁能帮我?

我也玩过JavaScript,并从这个YouTube教程开始。

似乎是相同的代码。

我改变了:

  1. const activeAnchor = document.querySelector("[data-page="+ CSS.escape(className) + "]");
  2. 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(; }

它有效,但不要问我为什么。

这是我的完整 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);
});

相关内容

  • 没有找到相关文章

最新更新