字数: 0 | 行数: 1
const editor = document.getElementById('editor');
const lineNumbers = document.getElementById('lineNumbers');
const stats = document.getElementById('stats');
function updateLineNumbers() {
const lines = editor.value.split('\n').length;
lineNumbers.innerHTML = Array.from({length: lines}, (_, i) => i + 1).join('\n');
}
function updateStats() {
const text = editor.value;
stats.textContent = `字数: ${text.length} | 行数: ${text ? text.split('\n').length : 1}`;
}
function updateAll() {
updateLineNumbers();
updateStats();
}
editor.addEventListener('input', updateAll);
editor.addEventListener('scroll', () => { lineNumbers.scrollTop = editor.scrollTop; });
editor.addEventListener('keydown', (e) => {
if (e.key === 'Tab') {
e.preventDefault();
const s = editor.selectionStart, end = editor.selectionEnd;
editor.value = editor.value.substring(0, s) + ' ' + editor.value.substring(end);
editor.selectionStart = editor.selectionEnd = s + 2;
updateAll();
}
if (e.key === 'Enter') {
e.preventDefault();
const s = editor.selectionStart;
const lineStart = editor.value.lastIndexOf('\n', s - 1) + 1;
const line = editor.value.substring(lineStart, s);
const indent = line.match(/^\s*/)[0];
const lastChar = editor.value.charAt(s - 1);
let extra = '';
if (lastChar === '{' || lastChar === '(' || lastChar === '[' || lastChar === ':') extra = ' ';
editor.value = editor.value.substring(0, s) + '\n' + indent + extra + editor.value.substring(editor.selectionEnd);
editor.selectionStart = editor.selectionEnd = s + 1 + indent.length + extra.length;
updateAll();
}
});
function updateLang() {
const lang = document.getElementById('langSelect').value;
const templates = {
javascript: '
python: '# Python 示例\ndef hello():\n print("Hello, World!")\n\nhello()',
java: '
c: '
go: '
};
if (!editor.value.trim()) editor.value = templates[lang] || '';
updateAll();
}
function copyCode() {
navigator.clipboard.writeText(editor.value).then(() => showToast('已复制到剪贴板'));
}
function clearEditor() {
if (!editor.value.trim() || confirm('确定要清空所有内容吗?')) {
editor.value = '';
updateAll();
}
}
function insertTab() {
const s = editor.selectionStart, end = editor.selectionEnd;
editor.value = editor.value.substring(0, s) + ' ' + editor.value.substring(end);
editor.selectionStart = editor.selectionEnd = s + 2;
editor.focus();
updateAll();
}
function removeTab() {
const s = editor.selectionStart;
const lineStart = editor.value.lastIndexOf('\n', s - 1) + 1;
const line = editor.value.substring(lineStart);
if (line.startsWith(' ')) {
editor.value = editor.value.substring(0, lineStart) + line.substring(2);
editor.selectionStart = editor.selectionEnd = Math.max(lineStart, s - 2);
editor.focus();
updateAll();
}
}
function toggleFullscreen() {
const c = document.getElementById('editorContainer');
c.classList.toggle('fullscreen');
}
function showToast(msg) {
const t = document.getElementById('toast');
t.textContent = msg;
t.classList.add('show');
setTimeout(() => t.classList.remove('show'), 2000);
}
updateAll();