正文
增加 370 行删除 130 行
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761773 行未改动1811821831841851861871881891901911921931941951961971981992002012022032042052062072082092 行未改动212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255### 前言在洛谷私信发一大段消息的时候,由于无法自动聚焦输入框,经常要点击,极大地影响了我们水谷的速度,所以做了这个插件(目前有自动聚焦输入框、更改自己的消息颜色和私信图片显示功能。### 源码将代码放到油猴里就行了。整个脚本最前端,有一块代码:```javascriptconst COLOR_CONFIG = {enableOwnMessageColor: true,// 是否启用自定义颜色ownMessageBgColor: "#d9f0ff",// 自己消息框的背景色ownMessageTextColor: "#000000" // 自己消息的文字颜色};```你可以修改参数的值来实现不同的效果。- `enableOwnMessageColor`:是否启用(自己的)消息框颜色修改功能,`true` 则启用;`false` 则不启用。- `ownMessageBgColor`:自己消息框的背景色,十六进制格式。- `ownMessageTextColor`:自己消息的文字颜色,十六进制格式。:::info[Luogu Chat Better!]{open}```javascript line-numbers// ==UserScript==// @name Luogu Chat Better!// @namespace http://tampermonkey.net/// @version 3.1// @description 洛谷私信 自动聚焦输入框 + 图片显示 + 颜色修改// @author Forever_Rain// @icon https://cdn.luogu.com.cn/upload/usericon/3.png// @match https://www.luogu.com.cn/chat*// @match https://www.luogu.com.cn/chat/*// @grant none// ==/UserScript==/* 用户自定义颜色配置 */const COLOR_CONFIG = {enableOwnMessageColor: true,// 是否启用自定义颜色ownMessageBgColor: "#d9f0ff",// 自己消息框的背景色ownMessageTextColor: "#000000" // 自己消息的文字颜色};/* 用户自设部分 */// 自动聚焦输入框(function() {'use strict';const inputSelectors = ['textarea.lg-message-input','textarea[name="content"]','.chat-input textarea','.message-editor textarea','div[contenteditable="true"]','textarea[placeholder*="私信"]','textarea[placeholder*="消息"]','textarea.lfe-form-sz-middle','.input-wrap textarea','#chat-input textarea'];const sendButtonSelectors = ['button[type="submit"]','button.send-btn','button:has(span:contains("发送"))','.send-button','.chat-send-btn'];function getInputElement() {for (const selector of inputSelectors) {const element = document.querySelector(selector);if (element && element.offsetParent !== null) { // 确保可见return element;}}const allTextareas = document.querySelectorAll('textarea');for (const ta of allTextareas) {if (ta.offsetParent !== null && (ta.placeholder?.includes('私信') || ta.placeholder?.includes('消息') || ta.closest('.chat-area'))) {return ta;}}const editableDivs = document.querySelectorAll('[contenteditable="true"]');for (const div of editableDivs) {if (div.offsetParent !== null && div.closest('.chat-area')) {return div;}}return null;}function focusInput(retries = 3) {// 重试:3次const input = getInputElement();if (input) {input.focus();if (input.isContentEditable) {const range = document.createRange();const sel = window.getSelection();range.selectNodeContents(input);range.collapse(false); // 折叠到末尾sel.removeAllRanges();sel.addRange(range);}} else if (retries > 0) {setTimeout(() => focusInput(retries - 1), 100);// 间隔0.1s}}function isSendButton(el) {if (!el) return false;const tag = el.tagName.toLowerCase();if (tag === 'button' || tag === 'input' && (el.type === 'submit' || el.type === 'button')) {const text = el.innerText || el.value || '';if (text.includes('发送') || text.includes('Send')) return true;if (el.classList && (el.classList.contains('send-btn') || el.classList.contains('chat-send-btn'))) return true;if (el.getAttribute('aria-label') === '发送') return true;}if (el.querySelector && el.querySelector('svg[data-icon="paper-plane"], svg[data-icon="send"]')) return true;return false;}function onDocumentClick(e) {let target = e.target;while (target && target !== document.body) {if (isSendButton(target)) {setTimeout(focusInput, 120);break;}target = target.parentElement;}}function onKeyDown(e) {// 检测 Ctrl+Enterif (e.ctrlKey && e.key === 'Enter') {const activeEl = document.activeElement;if (activeEl && (activeEl.tagName === 'TEXTAREA' || activeEl.isContentEditable)) {setTimeout(focusInput, 100);}}}document.addEventListener('click', onDocumentClick, true);document.addEventListener('keydown', onKeyDown);const observer = new MutationObserver((mutations) => {for (const mutation of mutations) {if (mutation.type === 'childList' && mutation.addedNodes.length) {const activeTag = document.activeElement?.tagName;if (activeTag !== 'TEXTAREA' && !document.activeElement?.isContentEditable) {const input = getInputElement();if (input && document.hasFocus()) {setTimeout(() => {if (document.activeElement !== input) {input.focus();}}, 200);}}break;}}});observer.observe(document.body, { childList: true, subtree: true });// 页面初始加载后,如果已有输入框且未聚焦,尝试聚焦一次(可选)window.addEventListener('load', () => {setTimeout(focusInput, 500);});})();// 图片显示(function() {'use strict';// 要搜索的 class 列表const searchClasses = ['message'];function replacePics(element) {if (!element) return;const walker = document.createTreeWalker(element, NodeFilter.SHOW_ELEMENT, {3 行未改动}return NodeFilter.FILTER_SKIP;}}, false);let node;while (node = walker.nextNode()) {var a = node.innerHTML.indexOf(";if(b == -1) break;var c = node.innerHTML.indexOf(")", b);if(c == -1) break;var link = node.innerHTML.substr(b + 2, c - b - 2);var text = node.innerHTML.substr(a + 2, b - a - 2);if(text == '') text = link;var regex = node.innerHTML.substr(a, c - a + 1);node.innerHTML = node.innerHTML.replace(regex, `<img style = "max-width: 516px;" src="${link}" alt="${text}">`);a = node.innerHTML.indexOf("![")}}}replacePics(document.body);// 监听DOMconst observer = new MutationObserver(mutations => {mutations.forEach(mutation => {if (mutation.type === 'childList') {mutation.addedNodes.forEach(node => {if (node.nodeType === Node.ELEMENT_NODE) {2 行未改动});}});});observer.observe(document.body, { childList: true, subtree: true });(function() {'use strict';// 读取const enable = COLOR_CONFIG.enableOwnMessageColor;if (!enable) {return;}const bgColor = COLOR_CONFIG.ownMessageBgColor;const textColor = COLOR_CONFIG.ownMessageTextColor;// 校验const isValidColor = (color) => /^#[0-9A-Fa-f]{6}$/.test(color);const finalBg = isValidColor(bgColor) ? bgColor : "#d9f0ff";const finalText = isValidColor(textColor) ? textColor : "#000000";// 注入自定义样式const styleId = "luogu-own-message-color-style";if (!document.getElementById(styleId)) {const style = document.createElement("style");style.id = styleId;style.textContent = `/* 自己发送的消息气泡背景 & 文字颜色 */.message-block.right .message {background-color: ${finalBg} !important;color: ${finalText} !important;}/* 调整气泡圆角等保持美观,不覆盖原有设计 */.message-block.right .message {border-radius: 12px !important;padding: 6px 12px !important;}`;document.head.appendChild(style);}})();})();```:::代码使用AI进行了**可读性调整**。1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192203 行未改动2242252262272282292302312322332342352362372382392402412422432442452462472482492502 行未改动253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495## 前言在洛谷私信发一大段消息的时候,由于无法自动聚焦输入框,经常要点击,极大地影响了我们水谷的速度,所以做了这个插件(## 使用左键点击消息会弹出菜单,有复制和回复消息功能。其他大部分为样式优化。## 设置整个脚本最前端,有一块代码:```javascriptconst CONFIG = {// 自己消息enableOwnColor: true,ownBgColor: "#d9f0ff",ownTextColor: "#000000",enableOwnRadius: true,// 对方消息enableOtherColor: false,otherBgColor: "",otherTextColor: "",enableOtherRadius: true,// 引用回复enableQuoteReply: true,quoteSeparator: " ||"};```你可以修改参数的值来实现不同的效果。### 自己消息| 配置项 | 类型 | 默认值 | 作用 ||--------|------|--------|------|| `enableOwnColor` | 布尔值 | `true` | 是否启用自己消息的颜色修改 || `ownBgColor` | 字符串 | `"#d9f0ff"` | 自己消息气泡的背景色 || `ownTextColor` | 字符串 | `"#000000"` | 自己消息的文字颜色 || `enableOwnRadius` | 布尔值 | `true` | 是否为自己消息应用圆角化 |### 对方消息| 配置项 | 类型 | 默认值 | 作用 ||--------|------|--------|------|| `enableOtherColor` | 布尔值 | `false` | 是否启用对方消息的颜色修改 || `otherBgColor` | 字符串 | `""`(洛谷默认) | 对方消息气泡的背景色 || `otherTextColor` | 字符串 | `""`(洛谷默认) | 对方消息的文字颜色 || `enableOtherRadius` | 布尔值 | `true` | 是否为对方消息应用圆角 |### 引用回复| 配置项 | 类型 | 默认值 | 作用 ||--------|------|--------|------|| `enableQuoteReply` | 布尔值 | `true` | 是否启用消息点击弹出菜单功能 || `quoteSeparator` | 字符串 | `" \|\|"` | 引用时插入到输入框前的分隔符 |## 源码:::info[Luogu Chat Better!]{open}```javascript line-numbers// ==UserScript==// @name Luogu Chat Better!// @namespace http://tampermonkey.net/// @version 5.3// @author Forever_Rain// @description 洛谷私信优化// @icon https://cdn.luogu.com.cn/upload/usericon/3.png// @match https://www.luogu.com.cn/chat// @match https://www.luogu.com.cn/chat/*// @match https://www.luogu.com.cn/chat?uid=*// @grant none// ==/UserScript==/******************** 用户自定义配置 ********************/const CONFIG = {// 自己消息enableOwnColor: true,ownBgColor: "#d9f0ff",ownTextColor: "#000000",enableOwnRadius: true,// 对方消息enableOtherColor: false,otherBgColor: "",otherTextColor: "",enableOtherRadius: true,// 引用回复enableQuoteReply: true,quoteSeparator: " ||"};/********************************************************/// 自动聚焦(function() {'use strict';function getInputElement() {let input = document.querySelector('textarea.lfe-form-sz-middle');if (input && input.offsetParent !== null) {return input;}const fallbackSelectors = ['textarea[name="content"]','.chat-input textarea','.message-editor textarea','.input-wrap textarea','#chat-input textarea'];for (const sel of fallbackSelectors) {const el = document.querySelector(sel);if (el && el.offsetParent !== null) {return el;}}return null;}function isSearchInput(el) {if (!el) return false;if (el.placeholder && el.placeholder.includes('搜索联系人')) return true;if (el.closest && el.closest('.side')) return true;return false;}function focusInput(retries = 5) {if (isSearchInput(document.activeElement)) return;const input = getInputElement();if (input) {if (document.activeElement !== input) {input.focus();if (input.isContentEditable) {const range = document.createRange();const sel = window.getSelection();range.selectNodeContents(input);range.collapse(false);sel.removeAllRanges();sel.addRange(range);}}} else if (retries > 0) {setTimeout(() => focusInput(retries - 1), 200);}}function isSendButton(el) {if (!el) return false;const tag = el.tagName.toLowerCase();if (tag === 'button' || (tag === 'input' && (el.type === 'submit' || el.type === 'button'))) {const text = el.innerText || el.value || '';if (text.includes('发送') || text.includes('Send')) return true;if (el.classList && (el.classList.contains('send-btn') || el.classList.contains('chat-send-btn'))) return true;if (el.getAttribute('aria-label') === '发送') return true;}if (el.querySelector && el.querySelector('svg[data-icon="paper-plane"], svg[data-icon="send"]')) return true;return false;}function onDocumentClick(e) {let target = e.target;while (target && target !== document.body) {if (isSendButton(target)) {setTimeout(focusInput, 150);break;}target = target.parentElement;}}function onKeyDown(e) {if (e.ctrlKey && e.key === 'Enter') {const active = document.activeElement;if (active && (active.tagName === 'TEXTAREA' || active.isContentEditable)) {setTimeout(focusInput, 150);}}}document.addEventListener('click', onDocumentClick, true);document.addEventListener('keydown', onKeyDown);const observer = new MutationObserver((mutations) => {if (isSearchInput(document.activeElement)) return;for (const mutation of mutations) {if (mutation.type === 'childList' && mutation.addedNodes.length) {const input = getInputElement();if (input && document.activeElement !== input && document.hasFocus()) {const active = document.activeElement;if (active && (active.tagName === 'TEXTAREA' || active.isContentEditable)) {if (active === input) return;}setTimeout(focusInput, 100);}break;}}});observer.observe(document.body, { childList: true, subtree: true });window.addEventListener('load', () => {setTimeout(focusInput, 500);});if (document.readyState === 'complete') {setTimeout(focusInput, 300);}})();// 图片显示(function() {'use strict';const searchClasses = ['message'];function replacePics(element) {if (!element) return;const walker = document.createTreeWalker(element, NodeFilter.SHOW_ELEMENT, {3 行未改动}return NodeFilter.FILTER_SKIP;}}, false);let node;while (node = walker.nextNode()) {let a = node.innerHTML.indexOf(";if(b == -1) break;let c = node.innerHTML.indexOf(")", b);if(c == -1) break;let link = node.innerHTML.substr(b + 2, c - b - 2);let text = node.innerHTML.substr(a + 2, b - a - 2);if(text == '') text = link;let regex = node.innerHTML.substr(a, c - a + 1);node.innerHTML = node.innerHTML.replace(regex, `<img style="max-width: 516px;" src="${link}" alt="${text}">`);a = node.innerHTML.indexOf("![");}}}replacePics(document.body);const observerPics = new MutationObserver(mutations => {mutations.forEach(mutation => {if (mutation.type === 'childList') {mutation.addedNodes.forEach(node => {if (node.nodeType === Node.ELEMENT_NODE) {2 行未改动});}});});observerPics.observe(document.body, { childList: true, subtree: true });})();// 自定义消息(function() {'use strict';const config = CONFIG;const isValidColor = (c) => /^#[0-9A-Fa-f]{6}$/.test(c);let css = '';if (config.enableOwnRadius || config.enableOwnColor) {const ownBg = (config.enableOwnColor && isValidColor(config.ownBgColor)) ? config.ownBgColor : '';const ownText = (config.enableOwnColor && isValidColor(config.ownTextColor)) ? config.ownTextColor : '';const ownRadius = config.enableOwnRadius ? 'border-radius: 12px !important;' : '';if (ownBg || ownText || ownRadius) {css += `.message-block.right .message {`;if (ownBg) css += ` background-color: ${ownBg} !important;`;if (ownText) css += ` color: ${ownText} !important;`;if (ownRadius) css += ` border-radius: 12px !important;`;css += ` padding: 6px 12px !important;`;css += ` }\n`;}}if (config.enableOtherRadius || config.enableOtherColor) {const otherBg = (config.enableOtherColor && isValidColor(config.otherBgColor)) ? config.otherBgColor : '';const otherText = (config.enableOtherColor && isValidColor(config.otherTextColor)) ? config.otherTextColor : '';const otherRadius = config.enableOtherRadius ? 'border-radius: 12px !important;' : '';if (otherBg || otherText || otherRadius) {css += `.message-block.left .message {`;if (otherBg) css += ` background-color: ${otherBg} !important;`;if (otherText) css += ` color: ${otherText} !important;`;if (otherRadius) css += ` border-radius: 12px !important;`;css += ` padding: 6px 12px !important;`;css += ` }\n`;}}css += `#quote-menu {display: none;position: fixed;background: #ffffff;border-radius: 10px;box-shadow: 0 4px 20px rgba(0,0,0,0.15);padding: 6px 0;min-width: 130px;z-index: 10000;font-size: 14px;color: #333;border: 1px solid #e8e8e8;user-select: none;}#quote-menu .menu-item {padding: 10px 24px;cursor: pointer;transition: background 0.15s;white-space: nowrap;}#quote-menu .menu-item:hover {background: #f0f4ff;}`;if (css.trim()) {const styleId = 'luogu-message-style-custom';let style = document.getElementById(styleId);if (!style) {style = document.createElement('style');style.id = styleId;document.head.appendChild(style);}style.textContent = css;}})();// 消息菜单(function() {'use strict';const config = CONFIG;if (!config.enableQuoteReply) return;function generateMarkdown(node) {let result = '';const stack = [node];while (stack.length) {const n = stack.shift();if (n.nodeType === Node.TEXT_NODE) {result += n.textContent;} else if (n.nodeType === Node.ELEMENT_NODE) {const tag = n.tagName.toLowerCase();if (n.classList && n.classList.contains('katex')) {const ann = n.querySelector('annotation[encoding="application/x-tex"]');const raw = ann ? ann.textContent.trim() : '';result += raw ? '$' + raw + '$' : n.textContent;} else if (tag === 'script' && n.type && /^math\/tex/.test(n.type)) {const raw = n.textContent.trim();result += (n.type.includes('block') || n.type.includes('display'))? '$$\n' + raw + '\n$$': '$' + raw + '$';} else if (tag === 'img') {const alt = n.getAttribute('alt') || '';const src = n.getAttribute('src') || '';if (src) result += '';} else if (tag === 'a') {const text = n.textContent;const href = n.getAttribute('href') || '';const isMention = text.trim().startsWith('@') || /\/user\//.test(href);const isBareURL = /^(https?:\/\/|www\.)/i.test(text.trim()) && !/\s/.test(text.trim());if (isMention || isBareURL) {result += text;} else {let inner = '';for (let i = 0; i < n.childNodes.length; i++) {inner += generateMarkdown(n.childNodes[i]);}if (inner === '') inner = text;result += '[' + inner + '](' + href + ')';}} else if (tag === 'strong' || tag === 'b') {result += '**' + n.textContent + '**';} else if (tag === 'em' || tag === 'i') {result += '*' + n.textContent + '*';} else if (tag === 'del' || tag === 's') {result += '~~' + n.textContent + '~~';} else if (tag === 'code') {result += '`' + n.textContent + '`';} else {for (let i = n.childNodes.length - 1; i >= 0; i--) {stack.unshift(n.childNodes[i]);}}}}return result.trim();}const menu = document.createElement('div');menu.id = 'quote-menu';const actions = [{ id: 'quote', label: '引用' },{ id: 'copy', label: '复制' }];actions.forEach(action => {const item = document.createElement('div');item.className = 'menu-item';item.dataset.action = action.id;item.textContent = action.label;menu.appendChild(item);});document.body.appendChild(menu);let currentMessageBlock = null;menu.addEventListener('click', function(e) {const item = e.target.closest('.menu-item');if (!item) return;const action = item.dataset.action;if (!action || !currentMessageBlock) return;const msgEl = currentMessageBlock.querySelector('.message');if (!msgEl) return;switch (action) {case 'quote': {const md = generateMarkdown(msgEl);if (!md) break;const textarea = document.querySelector('textarea.lfe-form-sz-middle');if (!textarea) break;const separator = config.quoteSeparator || '||';const content = separator + ' ' + md;textarea.value = content;textarea.focus();textarea.setSelectionRange(0, 0);textarea.dispatchEvent(new Event('input', { bubbles: true }));break;}case 'copy': {const textContent = msgEl.textContent;if (navigator.clipboard && navigator.clipboard.writeText) {navigator.clipboard.writeText(textContent).catch(() => {fallbackCopy(textContent);});} else {fallbackCopy(textContent);}function fallbackCopy(text) {const ta = document.createElement('textarea');ta.value = text;document.body.appendChild(ta);ta.select();document.execCommand('copy');ta.remove();}break;}}menu.style.display = 'none';currentMessageBlock = null;});document.addEventListener('click', function(e) {if (menu.style.display === 'none') return;if (!menu.contains(e.target)) {menu.style.display = 'none';currentMessageBlock = null;}});document.addEventListener('click', function(e) {if (menu.contains(e.target)) return;const block = e.target.closest('.message-block');if (!block) return;const msg = e.target.closest('.message');if (!msg) return;if (e.target.closest('a') || e.target.closest('img')) return;e.preventDefault();currentMessageBlock = block;menu.style.display = 'block';const x = Math.min(e.clientX, window.innerWidth - 160);const y = Math.min(e.clientY, window.innerHeight - 60);menu.style.left = x + 'px';menu.style.top = y + 'px';});})();```:::代码使用 `deepseek-R1` 进行了可读性调整。## 问题修复- [x] 在搜索框打字会跳转到输入框。- [x] 通过用户主页打开私信界面时没有匹配到。其他问题可以通过私信向作者反馈,集成该脚本在您的项目中也请提前征得作者同意。