版本比较
洛谷脚本2
正文
增加 16 行删除 16 行
164 行未改动全部展开165166167168169169170171172172173174175176176177178179179180181182183184184185186187187188189190191192193194195195196197198199200201201202203204205206207208209210210211212213213214215216217217218219220221222223224225226226227228229230231231232233234235235236237238239240241242243244244245246247248249250251252252253254255256708 行未改动全部展开164 行未改动全部展开// @author Jerrycyx & DeepSeek-R1// @match https://www.luogu.com.cn/problem/*// @grant none// ==/UserScript==
(function () { 'use strict';
// 等待目标元素加载 const readyCheck = setInterval(() => { const h2Elements = document.querySelectorAll('#app > div.main-container > main > div > div > div.main > div > h2');
let targetH2 = null; let targetDiv = null;
// 遍历所有h2元素,寻找textContent为"题目背景"的第一个元素 for (let i = 0; i < h2Elements.length; i++) { if (h2Elements[i].textContent.trim() === '题目背景') { targetH2 = h2Elements[i];
// 获取父节点下的下一个兄弟元素节点 let nextSibling = targetH2.nextElementSibling;
// 检查是否是div元素 if (nextSibling && nextSibling.tagName === 'DIV') { targetDiv = nextSibling; } break; // 找到第一个匹配项后立即退出循环 } }
if (targetH2 && targetDiv) { clearInterval(readyCheck); initializeToggleSystem(targetH2, targetDiv); } }, 100);
function initializeToggleSystem(h2Element, contentDiv) { // 创建包裹链接 const toggleLink = document.createElement('a'); toggleLink.href = 'javascript:void 0'; toggleLink.style.display = 'block'; toggleLink.style.width = 'fit-content'; h2Element.parentNode.replaceChild(toggleLink, h2Element); toggleLink.appendChild(h2Element);
// 获取题目唯一标识 const problemId = window.location.pathname.split('/problem/')[1].split('/')[0];
// 初始化状态 const savedState = localStorage.getItem(`luoguToggleState_${problemId}`); const initialState = savedState === 'hidden';
// 初始状态设置 if (initialState) { contentDiv.style.display = 'none'; insertStatusNotice(contentDiv); updateToggleText(toggleLink, false); } else { updateToggleText(toggleLink, true); }
// 点击事件处理 toggleLink.addEventListener('click', function () { const currentState = localStorage.getItem(`luoguToggleState_${problemId}`) === 'hidden'; const newState = !currentState;
contentDiv.style.display = newState ? 'none' : ''; updateToggleText(toggleLink, !newState); localStorage.setItem(`luoguToggleState_${problemId}`, newState ? 'hidden' : 'visible');
// 管理状态提示 const existingNotice = contentDiv.nextElementSibling?.classList?.contains('status-notice'); if (newState && !existingNotice) { insertStatusNotice(contentDiv); } else if (!newState && existingNotice) { contentDiv.nextElementSibling.remove(); } });
// 辅助函数 function insertStatusNotice(referenceNode) { const notice = document.createElement('p'); notice.textContent = '(已隐藏)'; notice.className = 'status-notice'; referenceNode.insertAdjacentElement('afterend', notice); }
function updateToggleText(linkElement, showText) { linkElement.querySelector('h2').textContent = `题目背景 - ${showText ? '显示' : '隐藏'}`; }708 行未改动全部展开