我正在研究一些项目的代码,其中项目显示在左侧。
活动类应该被添加到任何列表项的左行div的类中,但是,当我鼠标悬停在任何其他项目标题列表项上时,它只适用于第一个,我不是确定这是为什么?这是代码:
HTML:
<ul class="project">
<li class=project-title>
<div class="line-left"></div>
<p class="project-paragraph">Project title</p>
</li>
<li class=project-title>
<div class="line-left"></div>
<p class="project-paragraph">Project title</p>
</li>
<li class=project-title>
<div class="line-left"></div>
<p class="project-paragraph">Project title</p>
</li>
<li class=project-title>
<div class="line-left"></div>
<p class="project-paragraph">Project title</p>
</li>
<li class=project-title>
<div class="line-left"></div>
<p class="project-paragraph">Project title</p>
</li>
<li class=project-title>
<div class="line-left"></div>
<p class="project-paragraph">
Project title</p>
</li>
</ul>
CSS:
.project {
width: 170px;
font-family: Verdana, Geneva, sans-serif;
font-size: 14px;
color: #949394;
}
.project-title {
list-style: none;
cursor: pointer;
}
.project-paragraph {
display: inline-block;
}
.line-left {
border-top: 1px solid #2b2b2b;
width: 20px;
margin-top: 7px;
visibility: hidden;
display: inline-block;
margin-right: 10px;
padding-bottom: 4px;
}
.active {
visibility: visible;
}
JAVASCRIPT:
document.querySelector('.project-title').addEventListener('mouseover', function() {
document.querySelector('.project-title .line-left').classList.add('active');
});
以下是jsfiddle:https://jsfiddle.net/andylyell/ynb7wxk2/
我希望在一条线路上只剩下1个活动课程,但我不确定如何做到这一点。非常感谢任何帮助 - 谢谢!
答案 0 :(得分:0)
使用 -
document.querySelectorAll('.project-title').addEventListener('mouseover',
function() {
document.querySelectorAll('.project-title .line-
left').classList.add('active');
});
然后,您将能够将该类添加到具有该类的所有元素
答案 1 :(得分:0)
您必须订阅具有“project-title”类的每个元素。 以下是为您解决的修改过的js:
var activeClassName = 'active';
var elements = document.querySelectorAll('.project-title');
for (var i = 0; i < elements.length; i++) {
subscribeEvent(elements[i]);
}
function subscribeEvent(el) {
el.addEventListener('mouseover', function(e) {
var target = e.currentTarget;
if (containsClass(target.querySelector('.line-left'), activeClassName)) {
return;
}
setActiveEl(target);
}, false);
}
function setActiveEl(activeEl) {
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element != activeEl) {
removeClass(element.querySelector('.line-left'), activeClassName);
}
}
addClass(activeEl.querySelector('.line-left'), activeClassName);
}
function addClass(el, className) {
el && el.classList.add(className);
}
function removeClass(el, className) {
el && el.classList.remove(className);
}
function containsClass(el, className) {
return el && el.classList.contains(className);
}