Guard clause
const text = textInput.value;
// 字符数统计(包括空格)
characterCount.textContent = text.length;
// 字数统计(中文按字,英文按词)
let words = 0;
if (text.trim() !== '') {
// Match sequences of English letters/numbers or individual Chinese characters
const matches = text.match(/[a-zA-Z0-9]+|[\u4e00-\u9fa5]/g);
if (matches) {
words = matches.length;
}
}
wordCount.textContent = words;
// 段落数统计
const paragraphs = text.trim() === '' ? 0 :
text.split('\n').filter(para => para.trim().length > 0).length;
paragraphCount.textContent = paragraphs;
// 添加动画效果
[wordCount, characterCount, paragraphCount].forEach(el => {
if (el) { // Check if element exists
el.classList.add('pulse');
setTimeout(() => el.classList.remove('pulse'), 500);
}
});
}
// 事件监听
if (textInput) {
textInput.addEventListener('input', updateStats);
}
if (clearBtn) {
clearBtn.addEventListener('click', function() {
if (textInput) textInput.value = '';
updateStats();
if (textInput) textInput.focus();
});
}
if (sampleBtn) {
sampleBtn.addEventListener('click', function() {
const sampleText = `欢迎使用文章字数统计器!
这是一个示例文本,用于展示本工具的功能。您可以在此输入或粘贴您自己的文章内容,工具会自动统计字数、字符数和段落数。
本工具特别适合:
- 作家检查文章篇幅
- 学生统计作业字数
- 博主控制文章长度
- 内容创作者优化SEO
统计规则说明:
1. 字数:中文按字统计,英文按单词统计
2. 字符数:包括所有字符和空格
3. 段落数:按换行符分隔的非空段落
希望这个工具能帮助您更高效地进行创作!`;
if (textInput) textInput.value = sampleText;
updateStats();
if (textInput) textInput.focus();
});
}
// 初始化统计
updateStats();
}
// Expose the init function to the global scope for the template to call
window.initTextMetrics = initTextMetrics;
// Fallback for standalone operation: if not loaded within the template, initialize on DOMContentLoaded.
// The heuristic !document.getElementById('tool-content-container') checks if it's likely standalone.
if (!document.getElementById('tool-content-container')) {
if (document.readyState === 'complete' || document.readyState === 'interactive') {
console.warn('TextMetrics: Running in standalone mode (already loaded).');
initTextMetrics();
} else {
document.addEventListener('DOMContentLoaded', function() {
if (!document.getElementById('tool-content-container')) {
console.warn('TextMetrics: Running in standalone mode (DOMContentLoaded).');
initTextMetrics();
}
});
}
}