如何使HTML可折叠按钮默认为展开



我有一个带有多个可折叠按钮的HTML页面。我想在加载页面时展开一个按钮。目前,默认情况下,所有按钮都已折叠。如何更改HTML或CSS,使某个特定按钮(当前周(展开,其余按钮折叠?这是相关代码:

<!DOCTYPE html>
<html>
<head>
<title>
Prior_Recordings_HTML5
</title>
</head>
<link href="CSS/my_site.css" rel="stylesheet" type="text/css" />
<body>
<table class="table_for_collapse">
<tr>
<td>
<button class=collapsible>Current Week&mdash;November 8, 2020</button>
<div class=collapsible_content>
<a href="https://my_site_link_1" target="_blank" class="link3"
title="Sunday 11/8/2020">
Click here for Sunday, 11/8/2020<br />
</a>
<a href="https://my_site_link_2" target="_blank" class="link3"
title="Monday 11/9/2020">
Click here for 11/9/2020<br />
</a>
</div>
</td>
</tr>
<tr>
<td>
<button class=collapsible>Prior Week 1&mdash;November 1, 2020</button>
<div class=collapsible_content>
<a href="https://my_site_link_3" target="_blank" class="link3"
title="Sunday 11/1/2020">
Click here for Sunday, 11/1/2020<br />
</a>
<a href="https://my_site_link_4" target="_blank" class="link3"
title="Monday 11/2/2020">
Click here for 11/2/2020<br />
</a>
</div>
</td>
</tr>
</table>
<script>
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].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";
} 
});
}
</script>
</body>
</html>

这是CSS:

.collapsible {
background-color: #777;
color: white;
cursor: pointer;
font-size: 15px;
padding-top: 6px;
padding-bottom: 6px;
text-align: left;
width: 450px;
max-width: 1000px; 
}
.active, .collapsible:hover {
background-color: #555;
}
.collapsible:after {
content: '02B';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "2212";
}
.collapsible_content {
/*
padding: 0 18px;
*/
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #EEE8AA;
}

谢谢你看这个。

也许我不明白什么,但为什么不在主线程中运行eventlistener函数中运行的代码呢?

如果你以后处理日期,你可以为它制作一个单独的函数,比如:

function collapse_this_week(){
coll[0].classList.toggle("active");
var content = coll[0].nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
} 
}

您可以向函数传递一个参数,以确定根据开始使用日期的日期展开哪个按钮。

JSFiddle使用您的代码:此处

最新更新