本地小说阅读器
// ==UserScript==
// @name 本地小说阅读器
// @namespace http://tampermonkey.net/
// @version 5.3
// @description 修复翻页功能 + 优化快捷键判断
// @author sunhy
// @match *://*/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_addStyle
// @run-at document-end
// ==/UserScript==
(function() {
'use strict';
// ==================== 极简隐身样式 ====================
GM_addStyle(`
/* 触发区域 - 几乎看不见 */
.novel-trigger {
position: fixed;
left: 0;
top: 0;
width: 8px;
height: 100%;
background: transparent;
z-index: 999999;
cursor: pointer;
}
.novel-trigger:hover {
background: rgba(150,150,150,0.1);
}
/* 阅读器主窗口 - 极简半透明 */
.novel-reader {
position: fixed;
left: 15px;
top: 50px;
width: 400px;
height: 550px;
background: rgba(245,245,245,0.7);
border: none;
border-radius: 8px;
z-index: 999998;
display: flex;
flex-direction: column;
visibility: hidden;
opacity: 0;
transition: visibility 0.2s, opacity 0.2s;
backdrop-filter: blur(8px);
box-shadow: 0 4px 15px rgba(0,0,0,0.05);
color: #666;
resize: both;
overflow: hidden;
min-width: 250px;
min-height: 300px;
max-width: 800px;
max-height: 800px;
}
.novel-reader.open {
visibility: visible;
opacity: 1;
}
/* 标题栏 - 几乎看不见 */
.reader-header {
padding: 6px 12px;
background: transparent;
border-bottom: 1px solid rgba(0,0,0,0.03);
display: flex;
justify-content: space-between;
align-items: center;
cursor: move;
user-select: none;
height: 32px;
}
.reader-title {
color: #999;
font-size: 12px;
max-width: 180px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* 按钮 - 完全隐藏,仅保留功能 */
.reader-controls {
display: flex;
gap: 2px;
}
.reader-btn {
background: transparent;
border: none;
color: transparent;
width: 24px;
height: 24px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 0;
transition: none;
}
.reader-btn:hover {
background: rgba(0,0,0,0.03);
color: transparent;
}
/* 进度条 - 极淡 */
.progress-container {
padding: 0 12px;
background: transparent;
}
.progress-text {
font-size: 9px;
color: #ccc;
text-align: right;
padding: 2px 0;
}
.progress-bar {
height: 1px;
background: rgba(0,0,0,0.05);
margin-bottom: 4px;
}
.progress-fill {
height: 100%;
background: rgba(0,0,0,0.15);
width: 0%;
}
/* 搜索框 - 极简 */
.search-box {
padding: 4px 12px;
background: transparent;
display: flex;
gap: 4px;
align-items: center;
}
.search-box input {
flex: 1;
background: rgba(255,255,255,0.4);
border: 1px solid rgba(0,0,0,0.05);
padding: 3px 6px;
color: #666;
font-size: 11px;
border-radius: 3px;
}
.search-box input::placeholder {
color: #ccc;
}
.search-count {
color: #ccc;
font-size: 10px;
min-width: 40px;
}
/* 内容区域 */
.reader-content {
flex: 1;
overflow-y: auto;
padding: 15px 18px;
font-family: 'Microsoft YaHei', sans-serif;
font-size: 14px;
line-height: 1.7;
white-space: pre-wrap;
word-wrap: break-word;
color: #666;
background: transparent;
}
/* 搜索高亮 - 极淡 */
.search-highlight {
background: rgba(200,200,200,0.2);
border-radius: 1px;
}
.search-current {
background: rgba(150,150,150,0.25);
}
/* 状态栏 */
.reader-footer {
padding: 4px 12px;
background: transparent;
border-top: 1px solid rgba(0,0,0,0.02);
font-size: 10px;
color: #ccc;
display: flex;
justify-content: space-between;
height: 26px;
align-items: center;
}
/* 调整手柄 - 几乎看不见 */
.resize-handle {
position: absolute;
right: 0;
bottom: 0;
width: 15px;
height: 15px;
cursor: nwse-resize;
z-index: 100;
}
.resize-handle::after {
content: '';
position: absolute;
right: 3px;
bottom: 3px;
width: 6px;
height: 6px;
border-right: 1px solid rgba(0,0,0,0.1);
border-bottom: 1px solid rgba(0,0,0,0.1);
}
/* 快捷键提示 - 极淡 */
.shortcut-hint {
position: fixed;
bottom: 10px;
right: 10px;
background: rgba(240,240,240,0.3);
color: #ccc;
padding: 4px 10px;
border-radius: 16px;
font-size: 10px;
z-index: 1000000;
pointer-events: none;
backdrop-filter: blur(2px);
border: none;
}
`);
// ==================== 创建界面 ====================
const trigger = document.createElement('div');
trigger.className = 'novel-trigger';
trigger.title = '';
document.body.appendChild(trigger);
const reader = document.createElement('div');
reader.className = 'novel-reader';
reader.id = 'novelReader';
reader.innerHTML = `
<div class="reader-header" id="readerHeader">
<span class="reader-title" id="novelTitle"> </span>
<div class="reader-controls">
<button class="reader-btn" id="uploadBtn" title=""></button>
<button class="reader-btn" id="closeBtn" title=""></button>
</div>
</div>
<div class="progress-container">
<div class="progress-text" id="progressText"></div>
<div class="progress-bar"><div class="progress-fill" id="progressFill"></div></div>
</div>
<div class="search-box" id="searchBox" style="display: none;">
<input type="text" id="searchInput" placeholder="搜索">
<span class="search-count" id="searchCount"></span>
<button class="reader-btn" id="searchPrev"></button>
<button class="reader-btn" id="searchNext"></button>
<button class="reader-btn" id="searchClose"></button>
</div>
<div class="reader-content" id="novelContent"></div>
<div class="reader-footer">
<span id="fileInfo"></span>
<span id="posInfo"></span>
</div>
<div class="resize-handle" id="resizeHandle"></div>
<input type="file" id="fileInput" accept=".txt" style="display: none;">
`;
document.body.appendChild(reader);
const shortcutHint = document.createElement('div');
shortcutHint.className = 'shortcut-hint';
shortcutHint.innerHTML = '右键打开 | 左键收起 | 空格翻页 | ESC隐藏';
document.body.appendChild(shortcutHint);
// ==================== 状态变量 ====================
let novelContent = '';
let fileName = '';
let readerOpen = false;
let isHidden = false;
let isLoading = false;
const CHUNK_SIZE = 50000;
let currentChunk = 0;
let chunks = [];
let isDragging = false;
let dragOffsetX = 0, dragOffsetY = 0;
let isResizing = false;
let resizeStartX = 0, resizeStartY = 0;
let resizeStartWidth = 0, resizeStartHeight = 0;
let searchResults = [];
let currentSearchIndex = -1;
let searchTerm = '';
// ==================== 打开/关闭 ====================
function openReader() {
reader.classList.add('open');
readerOpen = true;
loadLastNovel();
}
function closeReader() {
reader.classList.remove('open');
readerOpen = false;
}
// ==================== 右键打开 / 左键收起 ====================
trigger.addEventListener('contextmenu', (e) => {
e.preventDefault();
e.stopPropagation();
if (!readerOpen) openReader();
});
trigger.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
if (readerOpen) closeReader();
});
// ==================== 拖动 ====================
const header = document.getElementById('readerHeader');
header.addEventListener('mousedown', (e) => {
if (e.target.tagName === 'BUTTON') return;
isDragging = true;
dragOffsetX = e.clientX - reader.offsetLeft;
dragOffsetY = e.clientY - reader.offsetTop;
reader.style.cursor = 'move';
e.preventDefault();
});
document.addEventListener('mousemove', (e) => {
if (isDragging) {
let newLeft = e.clientX - dragOffsetX;
let newTop = e.clientY - dragOffsetY;
newLeft = Math.max(0, Math.min(window.innerWidth - reader.offsetWidth, newLeft));
newTop = Math.max(0, Math.min(window.innerHeight - reader.offsetHeight, newTop));
reader.style.left = newLeft + 'px';
reader.style.top = newTop + 'px';
}
if (isResizing) {
const dx = e.clientX - resizeStartX;
const dy = e.clientY - resizeStartY;
let newWidth = resizeStartWidth + dx;
let newHeight = resizeStartHeight + dy;
newWidth = Math.max(250, Math.min(800, newWidth));
newHeight = Math.max(300, Math.min(800, newHeight));
reader.style.width = newWidth + 'px';
reader.style.height = newHeight + 'px';
}
});
document.addEventListener('mouseup', () => {
isDragging = false;
isResizing = false;
reader.style.cursor = 'default';
});
// ==================== 缩放 ====================
const resizeHandle = document.getElementById('resizeHandle');
resizeHandle.addEventListener('mousedown', (e) => {
e.preventDefault();
e.stopPropagation();
isResizing = true;
resizeStartX = e.clientX;
resizeStartY = e.clientY;
resizeStartWidth = reader.offsetWidth;
resizeStartHeight = reader.offsetHeight;
});
// ==================== 分页 ====================
function splitIntoChunks(text) {
const chunks = [];
for (let i = 0; i < text.length; i += CHUNK_SIZE) {
chunks.push(text.substring(i, Math.min(i + CHUNK_SIZE, text.length)));
}
return chunks;
}
function loadChunk(index) {
if (!chunks.length) return;
if (index < 0) index = 0;
if (index >= chunks.length) index = chunks.length - 1;
currentChunk = index;
document.getElementById('novelContent').innerHTML = chunks[index].replace(/\n/g, '<br>');
const progress = Math.round((index + 1) / chunks.length * 100);
document.getElementById('progressFill').style.width = progress + '%';
document.getElementById('progressText').textContent = progress + '%';
document.getElementById('posInfo').textContent = progress + '%';
GM_setValue('lastPosition', index);
}
function nextPage() {
console.log('下一页', currentChunk, chunks.length); // 调试
if (chunks.length && currentChunk < chunks.length - 1) {
loadChunk(currentChunk + 1);
}
}
function prevPage() {
console.log('上一页', currentChunk, chunks.length); // 调试
if (chunks.length && currentChunk > 0) {
loadChunk(currentChunk - 1);
}
}
// ==================== 文件上传 ====================
function handleFile(file) {
if (isLoading) return;
isLoading = true;
document.getElementById('novelContent').innerHTML = '<div style="text-align:center; padding:40px; color:#ccc;">加载中...</div>';
setTimeout(() => {
const fileReader = new FileReader();
fileReader.onload = (e) => {
novelContent = e.target.result;
fileName = file.name;
chunks = splitIntoChunks(novelContent);
document.getElementById('novelTitle').textContent = fileName.length > 25 ? fileName.substr(0,25)+'...' : fileName;
document.getElementById('fileInfo').textContent = chunks.length + '页';
loadChunk(0);
GM_setValue('lastNovel', novelContent);
GM_setValue('lastFile', fileName);
GM_setValue('lastPosition', 0);
isLoading = false;
};
fileReader.readAsText(file, 'UTF-8');
}, 100);
}
function loadLastNovel() {
const lastNovel = GM_getValue('lastNovel', '');
const lastFile = GM_getValue('lastFile', '');
const lastPos = GM_getValue('lastPosition', 0);
if (lastNovel && lastFile) {
novelContent = lastNovel;
fileName = lastFile;
chunks = splitIntoChunks(novelContent);
document.getElementById('novelTitle').textContent = fileName.length > 25 ? fileName.substr(0,25)+'...' : fileName;
document.getElementById('fileInfo').textContent = chunks.length + '页';
loadChunk(Math.min(lastPos, chunks.length - 1));
}
}
// ==================== 修复快捷键处理 ====================
document.addEventListener('keydown', (e) => {
const key = e.key;
const target = e.target;
const isInput = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable;
// 调试
console.log('按键:', key, '阅读器打开:', readerOpen, '输入框:', isInput);
// ESC隐藏 - 任何地方都可用
if (key === 'Escape') {
e.preventDefault();
isHidden = !isHidden;
const elements = [trigger, reader, shortcutHint];
elements.forEach(el => el.style.opacity = isHidden ? '0' : '1');
return;
}
// 左右键快速开关 - 任何地方都可用(只要不是输入框)
if (!isInput) {
if (key === 'ArrowLeft' && readerOpen) {
e.preventDefault();
closeReader();
return;
}
if (key === 'ArrowRight' && !readerOpen) {
e.preventDefault();
openReader();
return;
}
}
// 阅读器打开时的翻页功能 - 只要阅读器打开且不是输入框就可用
if (readerOpen && !isInput) {
// 翻页
if (key === ' ' || key === 'PageDown') {
e.preventDefault();
console.log('执行下一页');
nextPage();
return;
}
if (key === 'PageUp') {
e.preventDefault();
console.log('执行上一页');
prevPage();
return;
}
// 跳转
if (key === 'Home') {
e.preventDefault();
console.log('执行首页');
loadChunk(0);
return;
}
if (key === 'End') {
e.preventDefault();
console.log('执行末页');
loadChunk(chunks.length - 1);
return;
}
}
// 搜索快捷键 - 阅读器打开时可用
if (readerOpen && e.ctrlKey && key === 'f') {
e.preventDefault();
document.getElementById('searchBox').style.display = 'flex';
document.getElementById('searchInput').focus();
return;
}
// 关闭搜索
if (key === 'Escape' && document.getElementById('searchBox').style.display === 'flex') {
e.preventDefault();
clearSearch();
}
});
// ==================== 搜索功能 ====================
function search(text) {
if (!novelContent || !text || isLoading) {
clearSearch();
return;
}
searchTerm = text;
searchResults = [];
setTimeout(() => {
let pos = 0;
let count = 0;
const maxResults = 100;
while (count < maxResults) {
pos = novelContent.indexOf(text, pos);
if (pos === -1) break;
const chunkIndex = Math.floor(pos / CHUNK_SIZE);
searchResults.push({ pos, chunk: chunkIndex });
pos += text.length;
count++;
}
if (searchResults.length > 0) {
currentSearchIndex = 0;
const result = searchResults[0];
if (result.chunk !== currentChunk) {
loadChunk(result.chunk);
setTimeout(() => highlightSearch(), 100);
} else {
highlightSearch();
}
document.getElementById('searchCount').textContent = `${currentSearchIndex + 1}/${searchResults.length}`;
} else {
document.getElementById('searchCount').textContent = `0/0`;
}
document.getElementById('searchBox').style.display = 'flex';
}, 50);
}
function highlightSearch() {
if (!searchTerm || searchResults.length === 0) return;
let html = chunks[currentChunk];
const pageResults = searchResults.filter(r => r.chunk === currentChunk);
if (pageResults.length > 0) {
let lastPos = 0;
let newHtml = '';
pageResults.forEach((result, index) => {
const localPos = result.pos - (currentChunk * CHUNK_SIZE);
if (localPos >= 0 && localPos < chunks[currentChunk].length) {
newHtml += html.substring(lastPos, localPos).replace(/\n/g, '<br>');
const className = index === currentSearchIndex ? 'search-highlight search-current' : 'search-highlight';
newHtml += `<span class="${className}">${searchTerm}</span>`;
lastPos = localPos + searchTerm.length;
}
});
newHtml += html.substring(lastPos).replace(/\n/g, '<br>');
document.getElementById('novelContent').innerHTML = newHtml;
}
}
function nextSearch() {
if (searchResults.length === 0) return;
currentSearchIndex = (currentSearchIndex + 1) % searchResults.length;
const result = searchResults[currentSearchIndex];
if (result.chunk !== currentChunk) {
loadChunk(result.chunk);
setTimeout(() => highlightSearch(), 100);
} else {
highlightSearch();
}
document.getElementById('searchCount').textContent = `${currentSearchIndex + 1}/${searchResults.length}`;
}
function prevSearch() {
if (searchResults.length === 0) return;
currentSearchIndex = (currentSearchIndex - 1 + searchResults.length) % searchResults.length;
const result = searchResults[currentSearchIndex];
if (result.chunk !== currentChunk) {
loadChunk(result.chunk);
setTimeout(() => highlightSearch(), 100);
} else {
highlightSearch();
}
document.getElementById('searchCount').textContent = `${currentSearchIndex + 1}/${searchResults.length}`;
}
function clearSearch() {
searchResults = [];
currentSearchIndex = -1;
searchTerm = '';
document.getElementById('searchBox').style.display = 'none';
if (chunks[currentChunk]) {
document.getElementById('novelContent').innerHTML = chunks[currentChunk].replace(/\n/g, '<br>');
}
}
// ==================== 按钮事件(全透明)====================
document.getElementById('uploadBtn').addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
document.getElementById('fileInput').click();
});
document.getElementById('fileInput').addEventListener('change', (e) => {
if (e.target.files[0]) {
handleFile(e.target.files[0]);
openReader();
}
});
document.getElementById('closeBtn').addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
closeReader();
});
// ==================== 搜索事件 ====================
document.getElementById('searchInput').addEventListener('input', (e) => {
search(e.target.value);
});
document.getElementById('searchPrev').addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
prevSearch();
});
document.getElementById('searchNext').addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
nextSearch();
});
document.getElementById('searchClose').addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
clearSearch();
});
// ==================== 阻止事件冒泡 ====================
reader.addEventListener('mousedown', (e) => e.stopPropagation());
reader.addEventListener('click', (e) => e.stopPropagation());
// ==================== 启动 ====================
console.log('✅ 修复翻页版');
console.log(' - 翻页: 空格/PageDown');
console.log(' - 开关: ←/→键');
console.log(' - 隐藏: ESC');
})();