WordPress--代码块添加折叠和展开功能
原文网址:WordPress--代码块添加折叠和展开功能-CSDN博客
简介
本文介绍WordPress怎样给代码块添加折叠和展开功能。
问题描述
WordPress默认没有代码折叠功能,代码很长时看起来很不方便。
实现方案
本文使用纯javascript的方式,代码块增加折叠和展开功能。
如果行数超过了20,则自动折叠(设置代码块元素的max-height为20倍的行高),在代码最下方添加按钮:展开,点击展开后会展开(设置代码块元素的max-height为null),然后代码最下方按钮变为:折叠。点击折叠后,会重新折叠。
代码
// 获取所有的 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');}
});