var coll = document.getElementsByClassName("collapsible");
var p;
for (p = 0; p < coll.length; p++) {
coll[p].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
<button class="secondaryButton" id="Btn1"
onclick="Funtion();document.getElementById('humble').click()" /><a href="#humble">1. The Humble Beginning (1908-1944)</a>
<button class="collapsible" id="humble">The Humble Beginning (1908-1944)
</button>
<div class="content" id="humble2">
<div>content</div>
我使用上面的代码创建了一个触发可折叠内容打开的按钮。如何使按钮仅在内容折叠时起作用,而在内容打开时不起作用?
最佳答案
最简单的概念是,单击按钮后,始终检查目标是否已打开,如果已打开,则返回。由于上面的代码容易出错且不完整,下面尝试理顺。
<html>
<head>
<script>
function toggleContent(o) {
var contents = document.querySelectorAll(".collapsible .content");
for (var i=0; i<contents.length; i++) {
contents[i].style.display = 'none';
}
document.getElementById(o.dataset.target).style.display = 'block';
}
</script>
</head>
<body>
<div class="collapsible">
<button data-target="humble1" onclick="toggleContent(this)">1. The Humble Beginning (1908-1944)</button>
<button data-target="humble2" onclick="toggleContent(this)">2. The Humble Middle (1908-1944)</button>
<button data-target="humble3" onclick="toggleContent(this)">3. The Humble Ending (1908-1944)</button>
<div class="content" id="humble1">content 1</div>
<div class="content" id="humble2" style="display:none">content 2</div>
<div class="content" id="humble3" style="display:none">content 3</div>
</div>
</body>
</html>
基本上,单击每个按钮时,所有内容 block 都会隐藏,而目标保持打开状态。
关于javascript - 有条件工作的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49174428/