You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 querySelectorAll to grab all .title elements, then loop through each to attach a click handler.
  • e.preventDefault() stops the <a> tag from jumping to the top of the page (since its href="#").
  • this.parentElement targets the parent .content container, so we only select the .text block 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:22:57