JavaScript 导航栏 TypeError:'undefined' 不是对象 [关闭]
2021-09-12
83
我是 HTML、CSS 和 JavaScript 的新手。我收到错误,内容为:
TypeError: 'undefined' 不是对象
。现在我试图查找问题,但没有找到。有人能帮忙吗?控制台中出现错误:item.ClassList.container('active') && handleIndicator(item);
var indicator = document.querySelector('.indicator');
var items = document.querySelectorAll('.nav-item');
function handleIndicator(el) {
items.forEach(function(el) {
item.ClassList.remove('active');
item.removeAttribute('style');
});
indicator.style.width = "".concat(el.offsetWidth, "px");
indicator.style.left = "".concat(el.offsetLeft, "px");
indicator.style.backgroundColor = el.getAttribute('active-color');
el.ClassList.add('active');
el.style.color = el.Attributes('active-color');
}
items.forEach(function(item, index) {
item.addEventListener('click', function(e) {
handleIndicator(e.target);
});
item.ClassList.container('active') && handleIndicator(item);
});
<nav>
<a class="nav-item active" active-color="red">Test 1</a>
<a class="nav-item" active-color="blue">Test 2</a>
<a class="nav-item" active-color="purple">Test 3</a>
<a class="nav-item" active-color="pink">Test 4</a>
<div class="indicator"></div>
</nav>
2个回答
item.ClassList.remove('active');
应为
item.classList.remove('active');
。应为小写
Jagadeesh K
2021-09-12
尝试一下:
const indicator = document.querySelector('.indicator');
const items = document.querySelectorAll('.nav-item');
function handleIndicator(el) {
items.forEach(e => {
e.classList.remove('active');
e.removeAttribute('style');
});
indicator.style.width = "".concat(el.offsetWidth, "px");
indicator.style.left = "".concat(el.offsetLeft, "px");
indicator.style.backgroundColor = el.getAttribute('active-color');
el.classList.add('active');
el.style.color = el.getAttribute('active-color')
}
items.forEach(item => {
item.addEventListener('click', function(e) {
handleIndicator(e.target);
});
//item.classList.contains('active') && handleIndicator(item);
});
<nav>
<a class="nav-item active" active-color="red">Test 1</a>
<a class="nav-item" active-color="blue">Test 2</a>
<a class="nav-item" active-color="purple">Test 3</a>
<a class="nav-item" active-color="pink">Test 4</a>
<div class="indicator"></div>
</nav>
Nikola Pavicevic
2021-09-12