h5实现展开列表
实现展开列表的HTML5方法
使用HTML5和CSS3可以轻松实现展开列表效果,以下是几种常见的方法:
方法一:使用details和summary标签
<details>
<summary>点击展开列表</summary>
<ul>
<li>列表项1</li>
<li>列表项2</li>
<li>列表项3</li>
</ul>
</details>
方法二:使用CSS过渡效果
<style>
.expandable-list {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease-out;
}
.expandable-list.expanded {
max-height: 500px;
}
</style>
<button onclick="toggleList()">展开/收起</button>
<ul id="myList" class="expandable-list">
<li>项目1</li>
<li>项目2</li>
<li>项目3</li>
</ul>
<script>
function toggleList() {
document.getElementById('myList').classList.toggle('expanded');
}
</script>
方法三:使用jQuery实现动画效果
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<ul class="expandable">
<li class="header">标题</li>
<li class="content">内容1</li>
<li class="content">内容2</li>
</ul>
<style>
.content {
display: none;
}
</style>
<script>
$('.header').click(function() {
$(this).nextAll('.content').slideToggle();
});
</script>
响应式展开列表实现
对于移动设备友好的展开列表,可以结合媒体查询和触摸事件:
<style>
.responsive-list {
width: 100%;
}
.list-item {
padding: 10px;
border-bottom: 1px solid #ddd;
}
.list-content {
display: none;
padding: 15px;
}
@media (max-width: 768px) {
.list-header {
cursor: pointer;
}
}
</style>
<div class="responsive-list">
<div class="list-item">
<div class="list-header">标题1</div>
<div class="list-content">内容详情1</div>
</div>
<div class="list-item">
<div class="list-header">标题2</div>
<div class="list-content">内容详情2</div>
</div>
</div>
<script>
document.querySelectorAll('.list-header').forEach(header => {
header.addEventListener('click', () => {
const content = header.nextElementSibling;
content.style.display = content.style.display === 'block' ? 'none' : 'block';
});
});
</script>
可访问性考虑
为增强可访问性,建议添加ARIA属性和键盘导航支持:

<div class="accordion">
<button class="accordion-button" aria-expanded="false" aria-controls="panel1">
展开列表
</button>
<div id="panel1" class="accordion-content" hidden>
<ul>
<li>项目1</li>
<li>项目2</li>
</ul>
</div>
</div>
<style>
.accordion-button {
background: none;
border: none;
cursor: pointer;
}
.accordion-button[aria-expanded="true"]::before {
content: "▼ ";
}
.accordion-button[aria-expanded="false"]::before {
content: "► ";
}
</style>
<script>
document.querySelectorAll('.accordion-button').forEach(button => {
button.addEventListener('click', () => {
const expanded = button.getAttribute('aria-expanded') === 'true';
button.setAttribute('aria-expanded', !expanded);
document.getElementById(button.getAttribute('aria-controls')).hidden = expanded;
});
});
</script>
以上方法提供了从简单到复杂的多种实现方案,可根据项目需求选择合适的实现方式。






