如何创建显示/隐藏的JS脚本,反之亦然。在单击元素列表时根据其状态(display:none
或display:inline
)切换div?我在逻辑上挣扎...
这是我尝试过的小提琴Fiddle。
document.addEventListener('DOMContentLoaded', function() {
let panel = document.getElementsByClassName('panel');
let menu = document.getElementsByTagName('li');
console.log(menu, panel);
//recorre los elementos <li> y coloca un eventlistner 'click'
for (let i = 0; i < menu.length; i++) {
menu[i].addEventListener('click', function() {
//for(let j = 0; j < panel.length; j ++){
panel[i].style.display == 'inline' ? panel[i].style.display = 'inline' : panel[i].style.display = 'none';
//}
});
}
}, false);
#one {
display: inline;
}
#two {
display: none;
}
#three {
display: none;
}
#four {
display: none;
}
<ul>
<li>ONE</li>
<li>TWO</li>
<li>THREE</li>
<li>FOUR</li>
</ul>
<div class='panel' id='one'> ONE </div>
<div class='panel' id='two'> TWO </div>
<div class='panel' id='three'> THREE </div>
<div class='panel' id='four'> FOUR </div>
答案 0 :(得分:2)
您的panel display / hide
逻辑是错误的,我已更正,下面是工作示例
document.addEventListener('DOMContentLoaded', function() {
let panel = document.getElementsByClassName('panel');
let menu = document.getElementsByTagName('li');
for (let i = 0; i < menu.length; i++) {
menu[i].addEventListener('click', function() {
panel[i].style.display == 'inline' ? panel[i].style.display = 'none' : panel[i].style.display = 'inline';
});
}
}, false);
#one {
display: inline;
}
#two {
display: none;
}
#three {
display: none;
}
#four {
display: none;
}
<ul>
<li>ONE</li>
<li>TWO</li>
<li>THREE</li>
<li>FOUR</li>
</ul>
<div class='panel' id='one'> ONE </div>
<div class='panel' id='two'> TWO </div>
<div class='panel' id='three'> THREE </div>
<div class='panel' id='four'> FOUR </div>
答案 1 :(得分:0)
您可以使用onclick="MyFunction()"
(w3schools)来获得li元素的点击。
<ul>
<li onclick="handleClick(1)">Panel 1</li>
<li onclick="handleClick(2)">Panel 2</li>
<li onclick="handleClick(3)">Panel 3</li>
<li onclick="handleClick(4)">Panel 4</li>
</ul>
然后是一个简单的处理程序函数来捕获点击事件
var handleClick = function(index) {
let panel = document.getElementsByClassName('panel');
for (let i=0; i<panel.length; i++) {
panel[i].style.display = (index - 1) == i ? 'inline' : 'none';
}
};
查看我的工作fiddle。
另外,您的小提琴中有一个div结束标记错误。
<div class="one panel" id="one">
<div>
PANEL #1
</div>
<div class="two panel" id="two">
<div>
PANEL #2
</div>
</div>
</div>