WordPress--代码块添加折叠和展开功能

原文网址:WordPress--代码块添加折叠和展开功能-CSDN博客

简介

本文介绍WordPress怎样给代码块添加折叠和展开功能。

问题描述

WordPress默认没有代码折叠功能,代码很长时看起来很不方便。

实现方案

本文使用纯javascript的方式,代码块增加折叠和展开功能。

如果行数超过了20,则自动折叠(设置代码块元素的max-height为20倍的行高),在代码最下方添加按钮:展开,点击展开后会展开(设置代码块元素的max-height为null),然后代码最下方按钮变为:折叠。点击折叠后,会重新折叠。

代码

javascript 复制代码
// 获取所有的 pre 元素
const preElements = document.querySelectorAll('pre');

// 遍历每个 pre 元素
preElements.forEach((preElement) => {
    // 获取每个 pre 元素的高度和行数
    const lineHeight = parseInt(window.getComputedStyle(preElement).lineHeight);
    const height = preElement.offsetHeight;
    const lineCount = Math.floor(height / lineHeight);

    // 如果行数超过 20 行,则添加折叠效果
    if (lineCount > 20) {
        // 设置初始状态为折叠
        preElement.style.maxHeight = `${lineHeight * 20}px`;

        // 创建包裹容器
        const wrapper = document.createElement('div');
        wrapper.classList.add('pre-wrapper');

        // 将 pre 元素包裹在容器内
        preElement.parentNode.insertBefore(wrapper, preElement);
        wrapper.appendChild(preElement);

        // 添加展开/折叠按钮
        const expandButton = document.createElement('button');
        expandButton.textContent = '展开';
        expandButton.classList.add('expand-button');
        wrapper.appendChild(expandButton);

        // 展开/折叠按钮的点击事件处理程序
        expandButton.addEventListener('click', function() {
            if (!preElement.style.maxHeight) {
                // 已经展开,点击后折叠
                preElement.style.maxHeight = `${lineHeight * 20}px`;
                expandButton.textContent = '展开';
            } else {
                // 已经折叠,点击后展开
                preElement.style.maxHeight = null;
                expandButton.textContent = '折叠';
            }
        });

        // 设置容器的相对定位和水平居中样式
        wrapper.style.setProperty('position', 'relative');

        // 设置展开/折叠按钮的绝对定位和居中样式
        expandButton.style.setProperty('position', 'relative');
        expandButton.style.setProperty('top', `-${lineHeight * 1}px`);
        expandButton.style.setProperty('display', 'block');
        expandButton.style.setProperty('margin', '0 auto');
        expandButton.style.setProperty('padding', '3px');
    }
});

效果

相关推荐
GISer_Jing16 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩16 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车16 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
丷丩20 小时前
MapLibre GL JS第19课:实时更新要素
前端·javascript·gis·map·mapbox·maplibre gl js
xiaohua0708day21 小时前
Lodash库
前端·javascript·vue.js
突然好热21 小时前
TS 调试技巧
前端·javascript·typescript
h64648564h21 小时前
Flutter 国际化(i18n)全指南:一键切换中/英/日多语言
前端·javascript·flutter
丷丩1 天前
MapLibre GL JS第8课:禁用滚动缩放
javascript·mapbox·maplibre gl js
kyriewen1 天前
面试8家前端岗位后,我发现了一个残酷的事实:AI不是加分项,是门槛
前端·javascript·面试
MageGojo1 天前
做节日活动页时,如何用 API 快速生成对联内容
javascript·python·节日·对联生成