Tools 是非官方社区Wiki。社区文档正在编写中,欢迎参与。 Wiki编辑答疑群:717421103
版本250923.2
全站通知:

Widget:SyntaxhighlightCollapsible

来自WIKI实验室WIKI_BWIKI_哔哩哔哩
跳到导航 跳到搜索

为Syntaxhighlight标签增加高度限制,超过隐藏,可点击展开。代码完全由AI生成。

使用方式: 1. 为 syntaxhighlight 添加 class="collapsible" 2. 引入Widget {{#Widget:SyntaxhighlightCollapsible}}

代码:

<style>
div.mw-highlight.collapsible pre {
    max-height: 300px;
    overflow: hidden;
    transition: max-height 0.3s ease;
}

div.mw-highlight.collapsible pre.expanded {
    max-height: none;
}
</style><script>
(function () {
  'use strict';
  function runOnDOMReady(fn){ document.readyState==='loading' ? document.addEventListener('DOMContentLoaded', fn) : fn(); }
  function qsa(sel, root){ return Array.from((root||document).querySelectorAll(sel)); }

  runOnDOMReady(function(){
    // 为需要限制高度的代码块添加 class="collapsible"
    qsa('div.mw-highlight.collapsible').forEach(function(block){
      const pre = block.querySelector('pre');
      if (!pre || pre._expandBtnAdded) return;

      // 创建展开按钮
      const btn = document.createElement('button');
      btn.className = 'expand-code-btn';
      btn.textContent = '展开代码';
      btn.title = '点击展开完整代码';
      btn.style.cssText = 'position:absolute;bottom:8px;left:50%;transform:translateX(-50%);z-index:10;padding:4px 12px;font-size:12px;background:#666;color:#fff;border:none;border-radius:15px;cursor:pointer;opacity:.9;transition:all .2s';
      
      btn.onclick = function(){
         const isCollapsed = !pre.classList.contains('expanded');
         pre.classList.toggle('expanded', isCollapsed);
         btn.textContent = isCollapsed ? '收起代码' : '展开代码';
         btn.style.background = isCollapsed ? '#999' : '#666';
      };
      
      // 鼠标悬停效果
      btn.onmouseenter = function(){ this.style.opacity = '1'; };
      btn.onmouseleave = function(){ this.style.opacity = '.9'; };
      
      // 确保容器有相对定位
      if (getComputedStyle(block).position === 'static') {
        block.style.position = 'relative';
      }
      
      block.appendChild(btn);
      pre._expandBtnAdded = true; // 标记已处理
    });
  });
})();
</script>