Word/Character Count for Selected Text 字数统计器

Display word count for English or character count for Chinese in the selected text

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。

您需要先安装用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Word/Character Count for Selected Text 字数统计器
// @namespace    http://tampermonkey.net/
// @version      0.4
// @description  Display word count for English or character count for Chinese in the selected text
// @author       Welcome21984
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 创建显示字数的元素
    var countDiv = document.createElement('div');
    countDiv.style.position = 'fixed';
    countDiv.style.bottom = '20px';
    countDiv.style.right = '20px';
    countDiv.style.backgroundColor = 'rgba(0,0,0,0.5)';
    countDiv.style.color = 'white';
    countDiv.style.padding = '5px';
    countDiv.style.borderRadius = '5px';
    countDiv.style.zIndex = '1000';
    countDiv.style.display = 'none';
    document.body.appendChild(countDiv);

    // 检查是否包含中文字符
    function containsChinese(text) {
        return /[\u4e00-\u9fa5]/.test(text);
    }

    // 获取字数
    function getWordCount(text) {
        if (containsChinese(text)) {
            // 中文字符计数
            return text.length;
        } else {
            // 英文单词计数
            return text.trim().split(/\s+/).length;
        }
    }

    document.addEventListener('mouseup', function() {
        var selectedText = window.getSelection().toString();
        if (selectedText.length > 0) {
            var count = getWordCount(selectedText);
            countDiv.textContent = containsChinese(selectedText) ? "Character count: " + count : "Word count: " + count;
            countDiv.style.display = 'block';
        } else {
            countDiv.style.display = 'none';
        }
    });
})();