Greasy Fork

打码文字

按住Alt,选中文字,然后模糊

目前为 2023-11-02 提交的版本。查看 最新版本

// ==UserScript==
// @name         打码文字
// @version      0.1
// @description  按住Alt,选中文字,然后模糊
// @author       People11
// @match        *://*/*
// @namespace https://greasyfork.org/users/1143233
// ==/UserScript==

(function() {
    'use strict';

    function wrapTextWithSpan(textNode, start, end, style) {
        var span = document.createElement('span');
        for (var key in style) {
            span.style[key] = style[key];
        }

        var range = document.createRange();
        range.setStart(textNode, start);
        range.setEnd(textNode, end);
        range.surroundContents(span);
    }

    function processNode(node, style) {
        if (node.nodeType === Node.TEXT_NODE) {
            wrapTextWithSpan(node, 0, node.nodeValue.length, style);
        } else if (node.nodeType === Node.ELEMENT_NODE) {
            Array.from(node.childNodes).forEach(function(childNode) {
                processNode(childNode, style);
            });
        }
    }

    document.onmouseup = function(event) {
        if (event.altKey) {
            var selection = window.getSelection();
            if (!selection.isCollapsed) {
                var range = selection.getRangeAt(0);
                var commonAncestorContainer = range.commonAncestorContainer;

                // Style to be applied
                var style = {
                    filter: 'blur(5px)',
                    userSelect: 'none'
                };

                if (commonAncestorContainer.nodeType === Node.TEXT_NODE) {
                    wrapTextWithSpan(commonAncestorContainer, range.startOffset, range.endOffset, style);
                } else if (commonAncestorContainer.nodeType === Node.ELEMENT_NODE) {
                    Array.from(commonAncestorContainer.childNodes).forEach(function(childNode) {
                        if (selection.containsNode(childNode, true)) {
                            processNode(childNode, style);
                        }
                    });
                }

                selection.removeAllRanges();
            }
        }
    };
})();