JavaScript实现点击标题单独显示/隐藏对应文本区块的方法
Got it, let's fix this so you can toggle each section individually instead of all at once. Here's a clean, library-free solution using native JavaScript and CSS:
Step 1: Add CSS for hiding content
First, define a CSS class to handle the hidden state—this is more flexible than directly manipulating inline styles, and makes it easy to add animations later if you want:
/* 定义隐藏类,控制内容显示/隐藏 */ .hidden { display: none; } /* 可选:给标题加光标样式,提示用户可点击 */ .title { cursor: pointer; }
Step 2: Update your HTML (set initial state)
You can add the hidden class to any .text blocks you want hidden by default. If you want all sections open initially, just skip adding the class:
<div class="content"> <div class="title"><a href="#">Section 1</a></div> <div class="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et d...</div> </div> <div class="content"> <div class="title"><a href="#">Section 2</a></div> <div class="text hidden">Another text block for section 2...</div> </div> <div class="content"> <div class="title"><a href="#">Section 3</a></div> <div class="text hidden">Third section's content here...</div> </div>
Step 3: Add JavaScript for individual toggling
This code binds a click event to each title, and only targets the text block that belongs to that section:
// 获取所有标题元素 const sectionTitles = document.querySelectorAll('.title'); sectionTitles.forEach(title => { title.addEventListener('click', function(e) { // 阻止a标签默认的跳转行为(避免页面跳到顶部) e.preventDefault(); // 找到当前标题所属容器下的对应文本区块 const targetText = this.parentElement.querySelector('.text'); // 切换hidden类,实现显示/隐藏的切换 targetText.classList.toggle('hidden'); }); });
How this works:
- We use
querySelectorAllto grab all.titleelements, then loop through each to attach a click handler. e.preventDefault()stops the<a>tag from jumping to the top of the page (since itshref="#").this.parentElementtargets the parent.contentcontainer, so we only select the.textblock linked to the clicked title—no cross-talk between sections.classList.toggle('hidden')adds or removes the hidden class instantly, switching the text block's visibility.
Alternative: jQuery version (if you're using jQuery)
If your project already uses jQuery, you can simplify the JS to this concise version:
$('.title').click(function(e) { e.preventDefault(); // 直接找到同级的.text元素并切换类 $(this).siblings('.text').toggleClass('hidden'); });
内容的提问来源于stack exchange,提问作者Laura_Laurent

