如何用HTML、CSS、JavaScript实现点击标题展开段落(不使用jQuery)
纯原生JS实现标题点击折叠/展开段落
这里给你一套纯原生JS的实现方案,完全符合你的需求,不需要依赖jQuery:
1. 先写CSS样式(默认隐藏段落)
通过CSS让页面加载时段落处于折叠状态,同时给标题添加可点击的视觉提示:
/* 默认隐藏所有maincontent下的段落 */ .maincontent p { display: none; } /* 给标题添加点击光标,提示用户可交互 */ .maincontent h2 { cursor: pointer; position: relative; padding-left: 20px; /* 给前面的图标留出空间 */ } /* 标题前添加+/-图标,增强交互反馈 */ .maincontent h2::before { content: "+"; position: absolute; left: 0; } .maincontent h2.active::before { content: "-"; }
2. 原生JavaScript逻辑(绑定点击事件)
页面加载完成后,自动给所有标题绑定点击事件,实现折叠/展开切换:
// 等待页面DOM完全加载后执行 document.addEventListener('DOMContentLoaded', function() { // 获取所有maincontent容器 const contentBlocks = document.querySelectorAll('.maincontent'); // 遍历每个容器 contentBlocks.forEach(block => { const heading = block.querySelector('h2'); const paragraph = block.querySelector('p'); // 给标题绑定点击事件 heading.addEventListener('click', () => { // 切换段落显示状态 const isHidden = paragraph.style.display === 'none' || paragraph.style.display === ''; paragraph.style.display = isHidden ? 'block' : 'none'; // 切换标题的active类,更新图标 heading.classList.toggle('active'); }); }); });
3. 你的HTML结构无需修改
保持你原来的HTML代码即可,上述代码会自动适配所有.maincontent下的标题和段落:
<div class="maincontent"> <h2>How HowziTO came to be? </h2> <p> This website was created by me, a South African who moved to Toronto in my mid 20's. Through the move, I felt unprepared, and at times, alone. Although there are many sites that offer advice to new immigrants, I thought it would be useful to create a site that is specific to South Africans, given our unique heritage. So, if you feel like I felt, hopefull this website will help you settle in a little easier. If you have any suggestions for the site, please feel free to reach out to me using the <a href="About.html">the about page</a>. </p> </div>
功能说明
- 页面加载时所有段落默认隐藏,满足初始折叠要求
- 点击任意标题,只会切换当前区块内的段落状态,不会影响其他内容
- 纯原生实现,没有引入任何外部库,适合课程作业场景
- 标题前的+/-图标可以直观反馈当前折叠状态,不需要可以删除CSS里的伪元素部分
内容的提问来源于stack exchange,提问作者Warwick Watt
相关产品推荐
相关产品推荐

