首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

原生 JavaScript 實現頁面內容收起/展開切換效果的完整代碼示例

     編輯:程式設計疑難解答

完整可運行代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
  .detail { display: none; margin-top: 5px; padding: 10px; background: #f5f5f5; border-radius: 4px; }
  .toggle-btn { cursor: pointer; color: #0066cc; text-decoration: underline; }
  .toggle-btn:hover { color: #cc0000; }
</style>
</head>
<body>

<a href="javascript:void(0)" class="toggle-btn" onclick="toggle('detail1', this)">展開內容 1</a>
<div id="detail1" class="detail">這是第一段詳細內容...</div>

<a href="javascript:void(0)" class="toggle-btn" onclick="toggle('detail2', this)">展開內容 2</a>
<div id="detail2" class="detail">這是第二段詳細內容...</div>

<script>
function toggle(id, btn) {
  var el = document.getElementById(id);
  if (el.style.display === 'none') {
    el.style.display = 'block';
    btn.textContent = '收起 ' + btn.textContent.replace('展開', '');
  } else {
    el.style.display = 'none';
    btn.textContent = btn.textContent.replace('收起', '展開');
  }
}
</script>
</body>
</html>

核心邏輯

  • 使用 display: none/block 控制顯隱。
  • 按鈕文本動態切換「展開/收起」。
  • 無需 jQuery,原生 JS 體積極小,兼容所有瀏覽器。

進階增強

  • 添加 CSS Transition 實現滑動動畫:.detail { max-height: 0; overflow: hidden; transition: max-height 0.3s; } 配合 JS 設置 max-height: scrollHeight。
  • 使用 <details><summary> 原生標簽(HTML5.1),零 JS 實現同樣效果。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved